//
//  MaintenanceDetailedViewController.m
//  FMS
//
//  Created by Steven on 10/16/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "MaintenanceDetailedViewController.h"
#import "MaintenanceTypeViewController.h"
#import "ScheduleInspectionViewController.h"
#import "ApprovedViewController.h"
#import "BuildingMgmtViewController.h"
#import "DetailedItemViewController.h"
#import "EformViewController.h"
#import "ListMaintenanceAttachmentViewController.h"
#import "ListOptionsViewController.h"

@interface MaintenanceDetailedViewController ()

@end

@implementation MaintenanceDetailedViewController
@synthesize parent;
@synthesize isEdit;
@synthesize itemDetailDict;
@synthesize itemType;
@synthesize titleContainerView;
@synthesize personInChargeDict;
@synthesize typeRequirementDict;
@synthesize inputMaintenanceDict;
@synthesize inputInspectionDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent serviceType:(int)_serviceType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        parent = _parent;
        serviceType = _serviceType;
        
        mainArray = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (IBAction)backPreviousView:(id)sender {
    NSError *error;
    if (!isEdit) {
        //delete temporary maintenance
        if (inputMaintenanceDict != Nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[inputMaintenanceDict objectForKey:@"_id"] error:&error];
            if (!error) {
                NSLog(@"delete temporary maintenance successfully");
            }
        }
        else if (inputInspectionDict != nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[inputInspectionDict objectForKey:@"_id"] error:&error];
            if (!error) {
                NSLog(@"delete temporary inspection successfully");
            }
        }
    }
    else {
        if (newInspectionId != nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:newInspectionId error:&error];
            if (!error) {
                NSLog(@"delete temporary new inspection successfully");
            }
            
            //reload previous inspection
            if (beforeInspectionSavedDict != nil) {
                NSError *error;
                [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeInspectionSavedDict error:&error];
                if (!error) {
                    NSLog(@"reload previous Inspection successfully");
                }
            }
        }
        
        if (newScheduleId != nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:newScheduleId error:&error];
            if (!error) {
                NSLog(@"delete temporary new schedule successfully");
            }
            
            //reload previous schedule
            NSError *error;
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeScheduleSavedDict error:&error];
            if (!error) {
                NSLog(@"reload previous Schedule successfully");
            }
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)handleRightCornerEvent:(id)sender {
    if (serviceType == Maintenance) {
        ListOptionsViewController *controller = [[ListOptionsViewController alloc] initWithStyle:UITableViewStylePlain parent:self];
        
        popController = [[UIPopoverController alloc] initWithContentViewController:controller];
        [popController presentPopoverFromRect:_btnRightCorner.frame inView:_mainTitleContainerView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        
    }
    else {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //set to No to reload view after tap Save.
        [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:@"isSelectDetail"];
        NSString *userId = [userDefaults objectForKey:ACCOUNT_ID];
        
        NSString *checkList = @"0";
        NSString *technicalAssessment = @"0";
        NSString *report = @"0";
        NSString *startDate = @"";
        
        //get all objects in section 1 and set value
        for (int i=0;i < [mainArray count];i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
            UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
            
            NSMutableDictionary *dict = [mainArray objectAtIndex:i];
            for (id subview in cell.contentView.subviews) {
                //validate type of requirement
                if (((UIButton*)subview).tag == filter_inspection) {
                    if ([[dict objectForKey:@"objectValue"] isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.type-of-requirement-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                }
                else if (((UIButton*)subview).tag == filter_start_date) {
                    startDate = [dict objectForKey:@"objectValue"];
                    if ([startDate isEqualToString:@""] || startDate == nil) {
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.start-date-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                }
                else if (((UIButton*)subview).tag == filter_person_in_charge) {
#ifndef vDEBUG
                    NSString *personInCharge = [dict objectForKey:@"objectValue"];
                    if ([personInCharge isEqualToString:[dictLanguage objectForKey:@"schedule.title-select-liaison"]] ||  [personInCharge isEqualToString:@""] || personInCharge == nil) {
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.person-in-charge-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
#endif
                }
                else if ([subview isKindOfClass:[DCRoundSwitch class]]) {
                    //get value of switch
                    int objectType = [[dict objectForKey:@"objectType"] intValue];
                    if (objectType == m_Checklist)
                        checkList = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
                    else if (objectType == m_Technical_Assessment) {
                        technicalAssessment = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
                    }
                    else if (objectType == m_Report) {
                        report = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
                    }
                }
            }
        }
        
        NSString *maintenanceTypeIdStr = [itemDetailDict objectForKey:@"maintenanceTypeId"] == Nil ? @"" : [itemDetailDict objectForKey:@"maintenanceTypeId"];
        if (!isEdit) {
            NSString *itemName = [NSString stringWithFormat:@"%@, %@",[itemDetailDict objectForKey:@"item_name"],[itemDetailDict objectForKey:@"building"]];
            //create new Inspection and assign scheduleId
            
            [inputInspectionDict setObject:itemName forKey:@"itemName"];
            [inputInspectionDict setObject:startDate forKey:@"startDate"];
            [inputInspectionDict setObject:@"" forKey:@"lastDone"];
            [inputInspectionDict setObject:checkList forKey:@"checkList"];
            [inputInspectionDict setObject:technicalAssessment forKey:@"technicalAssessment"];
            [inputInspectionDict setObject:report forKey:@"report"];
            [inputInspectionDict setObject:[NSNumber numberWithBool:workCompleteSwitch.on] forKey:@"workComplete"];
            [inputInspectionDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
            [inputInspectionDict setObject:[itemDetailDict objectForKey:@"_id"] forKey:@"itemId"];
            [inputInspectionDict setObject:[NSNumber numberWithBool:inspectionResultSwitch.on] forKey:@"inspectionResult"];
            [inputInspectionDict setObject:[NSNumber numberWithBool:followActionSwitch.on] forKey:@"followAction"];
            
            if (!workCompleteSwitch.on) {
                //if workComplete = NO, create new inspection
                //firstly, we create new schedule for this inspection, then assign the _id of this schedule for Inspection document
                //create new scheduling
                NSMutableDictionary *dictSchedule = [NSMutableDictionary dictionaryWithObjectsAndKeys:kScheduleDocType,@"Table",userId,@"userId",[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"],@"scheduleCategory",[itemDetailDict objectForKey:@"camp"],@"camp",[itemDetailDict objectForKey:@"service"],@"service",[itemDetailDict objectForKey:@"unit"],@"unit",[itemDetailDict objectForKey:@"building"],@"building",[itemDetailDict objectForKey:@"floor"],@"floor",[itemDetailDict objectForKey:@"item_name"],@"room",[NSNumber numberWithInt:1],@"typeRequirement",startDate,@"startDate",@"",@"lastDone",@"",@"lastUpdate",personInChargeDict,@"personInCharge",@"",@"reMark",maintenanceTypeIdStr,@"maintenanceTypeId",[ApplicationDelegate getMaintenanceName:[maintenanceTypeIdStr intValue]],@"maintenanceType",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated",[NSNumber numberWithInt:itemType],@"itemType",[NSNumber numberWithInt:Inspection],@"categoryId",[NSNumber numberWithBool:NO],@"wasRead",[itemDetailDict objectForKey:@"_id"],@"itemId",[typeRequirementDict objectForKey:@"index"],@"categoryTypeId",[typeRequirementDict objectForKey:@"filterName"],@"categoryType",nil];
                
                NSError *error;
                [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:dictSchedule error:&error];
                if (!error) {
                    //success
                    NSString *scheduleId = [dictSchedule objectForKey:@"_id"];
                    [inputInspectionDict setObject:scheduleId forKey:@"scheduleId"];
                    
                    NSError *error;
                    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inputInspectionDict error:&error];
                    if (!error) {
                        //update inspectionId for scheduleDoc
                        [dictSchedule setObject:[inputInspectionDict objectForKey:@"_id"] forKey:@"inspectionId"];
                        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictSchedule error:&error];
                        
                        //success
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                    }
                }
            }
            else {
                if (!inspectionResultSwitch.on) {
                    //inspection failed
                    [userDefaults setObject:[NSNumber numberWithBool:YES] forKey:IS_INSPECTION_FAILED];
                    
                    MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
                    controller.itemDetailedDict = [itemDetailDict mutableCopy];
                    [controller.itemDetailedDict setObject:[itemDetailDict objectForKey:@"_id"] forKey:@"itemId"];
                    controller.inputInspectionDict = inputInspectionDict;
                    controller.theNewInspectionId = newInspectionId;
                    controller.theNewScheduleId = newScheduleId;
                    controller.beforeInspectionSavedDict = beforeInspectionSavedDict;
                    controller.beforeScheduleSavedDict = beforeScheduleSavedDict;
                    
                    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
                    navController.modalPresentationStyle = UIModalPresentationPageSheet;
                    [self presentModalViewController:navController animated:YES];
                    
                    if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                        navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
                }
                else {
                    //inspection passed
                    //check follow up action
                    if (!followActionSwitch.on) {
                        //add inspection directly, similar to the workComplete = NO case
                        //firstly, we create new schedule for this inspection, then assign the _id of this schedule for Inspection document
                        //create new scheduling
                        NSMutableDictionary *dictSchedule = [NSMutableDictionary dictionaryWithObjectsAndKeys:kScheduleDocType,@"Table",userId,@"userId",[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"],@"scheduleCategory",[itemDetailDict objectForKey:@"camp"],@"camp",[itemDetailDict objectForKey:@"service"],@"service",[itemDetailDict objectForKey:@"unit"],@"unit",[itemDetailDict objectForKey:@"building"],@"building",[itemDetailDict objectForKey:@"floor"],@"floor",[itemDetailDict objectForKey:@"item_name"],@"room",[NSNumber numberWithInt:1],@"typeRequirement",startDate,@"startDate",@"",@"lastDone",@"",@"lastUpdate",personInChargeDict,@"personInCharge",@"",@"reMark",maintenanceTypeIdStr,@"maintenanceTypeId",[ApplicationDelegate getMaintenanceName:[maintenanceTypeIdStr intValue]],@"maintenanceType",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated",[NSNumber numberWithInt:itemType],@"itemType",[NSNumber numberWithInt:Inspection],@"categoryId",[NSNumber numberWithBool:NO],@"wasRead",[itemDetailDict objectForKey:@"_id"],@"itemId",[typeRequirementDict objectForKey:@"index"],@"categoryTypeId",[typeRequirementDict objectForKey:@"filterName"],@"categoryType",nil];
                        
                        NSError *error;
                        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:dictSchedule error:&error];
                        if (!error) {
                            //success
                            NSString *scheduleId = [dictSchedule objectForKey:@"_id"];
                            
                            NSString *itemName = [NSString stringWithFormat:@"%@, %@",[itemDetailDict objectForKey:@"item_name"],[itemDetailDict objectForKey:@"building"]];
                            
                            [inputInspectionDict setObject:scheduleId forKey:@"scheduleId"];
                            [inputInspectionDict setObject:itemName forKey:@"itemName"];
                            [inputInspectionDict setObject:startDate forKey:@"startDate"];
                            [inputInspectionDict setObject:@"" forKey:@"lastDone"];
                            [inputInspectionDict setObject:checkList forKey:@"checkList"];
                            [inputInspectionDict setObject:technicalAssessment forKey:@"technicalAssessment"];
                            [inputInspectionDict setObject:report forKey:@"report"];
                            [inputInspectionDict setObject:[NSNumber numberWithBool:workCompleteSwitch.on] forKey:@"workComplete"];
                            [inputInspectionDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                            [inputInspectionDict setObject:[itemDetailDict objectForKey:@"_id"] forKey:@"itemId"];
                            [inputInspectionDict setObject:[NSNumber numberWithBool:inspectionResultSwitch.on] forKey:@"inspectionResult"];
                            [inputInspectionDict setObject:[NSNumber numberWithBool:followActionSwitch.on] forKey:@"followAction"];
                            
                            NSError *error;
                            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inputInspectionDict error:&error];
                            if (!error) {
                                //update inspectionId for scheduleDoc
                                [dictSchedule setObject:[inputInspectionDict objectForKey:@"_id"] forKey:@"inspectionId"];
                                [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictSchedule error:&error];
                                
                                //success
                                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                                [dialog show];
                                
                                //add new inspection for next cycle
                                //create new inspection and new schedule with the new last done
                                NSMutableDictionary *newScheduleDict = [dictSchedule mutableCopy];
                                [newScheduleDict removeObjectForKey:@"_id"];
                                [newScheduleDict removeObjectForKey:@"_rev"];
                                
                                NSString *scheduleId = @"";
                                startDate = [newScheduleDict objectForKey:@"startDate"];
                                
                                //calculate the new next done
                                
                                int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                                NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                                
                                NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                                
                                [newScheduleDict setObject:lastDate forKey:@"startDate"];
                                //set startDate to lastUpdate field
                                [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                                [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                
                                [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                                if (!error) {
                                    newScheduleId = [newScheduleDict objectForKey:@"_id"];
                                    scheduleId = [newScheduleDict objectForKey:@"_id"];
                                    NSString *itemName = [NSString stringWithFormat:@"%@, %@",[itemDetailDict objectForKey:@"item_name"],[itemDetailDict objectForKey:@"building"]];
                                    
                                    NSMutableDictionary *newInspectionDict = [inputInspectionDict mutableCopy];
                                    [newInspectionDict removeObjectForKey:@"_id"];
                                    [newInspectionDict removeObjectForKey:@"_rev"];
                                    
                                    [newInspectionDict setObject:scheduleId forKey:@"scheduleId"];
                                    [newInspectionDict setObject:lastDate forKey:@"startDate"];
                                    [newInspectionDict setObject:startDate forKey:@"lastUpdate"];
                                    [newInspectionDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                                    [newInspectionDict setObject:[NSNumber numberWithBool:NO] forKey:@"status"];
                                    [newInspectionDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                    //create new inspection
                                    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newInspectionDict error:&error];
                                    newInspectionId = [newInspectionDict objectForKey:@"_id"];
                                }
                            }
                        }
                    }
                    else {
                        //if follow action
                        [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:IS_INSPECTION_FAILED];
                        
                        MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
                        controller.itemDetailedDict = [itemDetailDict mutableCopy];
                        [controller.itemDetailedDict setObject:[itemDetailDict objectForKey:@"_id"] forKey:@"itemId"];
                        controller.inputInspectionDict = inputInspectionDict;
                        controller.theNewInspectionId = newInspectionId;
                        controller.theNewScheduleId = newScheduleId;
                        controller.beforeInspectionSavedDict = beforeInspectionSavedDict;
                        controller.beforeScheduleSavedDict = beforeScheduleSavedDict;
                        
                        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
                        navController.modalPresentationStyle = UIModalPresentationPageSheet;
                        [self presentModalViewController:navController animated:YES];
                        
                        if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                            navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
                    }
                }
            }
        }
        else {
            //update inspection
            CBLDocument *inspectionDoc = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[itemDetailDict objectForKey:@"_id"]];
            beforeInspectionSavedDict = [inspectionDoc.properties mutableCopy];
            NSMutableDictionary *inspectionDict = [inspectionDoc.properties mutableCopy];
            [inspectionDict setObject:checkList forKey:@"checkList"];
            [inspectionDict setObject:technicalAssessment forKey:@"technicalAssessment"];
            [inspectionDict setObject:report forKey:@"report"];
            [inspectionDict setObject:[NSNumber numberWithBool:workCompleteSwitch.on] forKey:@"workComplete"];
            [inspectionDict setObject:[NSNumber numberWithBool:inspectionResultSwitch.on] forKey:@"inspectionResult"];
            [inspectionDict setObject:[NSNumber numberWithBool:followActionSwitch.on] forKey:@"followAction"];
            [inspectionDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
            NSError *error;
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inspectionDict error:&error];
            if (!error) {
                NSString *maintenanceId = [itemDetailDict objectForKey:@"maintenanceId"];
                
                /***** calculate next done and last done after update inspection ********/
                
                CBLDocument *scheduleDoc = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[itemDetailDict objectForKey:@"scheduleId"]];
                
                //update schedule status for this inspection to notify
                beforeScheduleSavedDict = [scheduleDoc.properties mutableCopy];
                NSMutableDictionary *scheduleDict = [scheduleDoc.properties mutableCopy];
                [scheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                [scheduleDict setObject:[NSNumber numberWithBool:NO] forKey:@"wasRead"];
                
                NSError *error;
                [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:scheduleDict error:&error];
                if (!error) {
                    NSLog(@"update schedule for Inspection successfully");
                }
                
                if (workCompleteSwitch.on) {
                    //create new inspection and new schedule with the new last done
                    NSMutableDictionary *newScheduleDict = [scheduleDoc.properties mutableCopy];
                    NSString *scheduleId = @"";
                    startDate = [newScheduleDict objectForKey:@"startDate"];
                    
                    //calculate the new next done
                    
                    int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                    NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                    
                    NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                    
                    [newScheduleDict setObject:lastDate forKey:@"startDate"];
                    //set startDate to lastUpdate field
                    [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                    [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                    
                    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                    if (!error) {
                        newScheduleId = [newScheduleDict objectForKey:@"_id"];
                        scheduleId = [newScheduleDict objectForKey:@"_id"];
                        NSString *itemName = [NSString stringWithFormat:@"%@, %@",[itemDetailDict objectForKey:@"item_name"],[itemDetailDict objectForKey:@"building"]];
                        
                        NSMutableDictionary *newInspectionDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemName,@"itemName",startDate,@"startDate",@"",@"lastDone",checkList,@"checkList",technicalAssessment,@"technicalAssessment",report,@"report",scheduleId,@"scheduleId",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated",InspectionDoc,@"Table",[itemDetailDict objectForKey:@"itemId"],@"itemId",[NSNumber numberWithBool:NO],@"workComplete",[NSNumber numberWithBool:NO],@"inspectionResult",[NSNumber numberWithBool:NO],@"followAction",userId,@"userId", nil];
                        //create new inspection
                        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newInspectionDict error:&error];
                        newInspectionId = [newInspectionDict objectForKey:@"_id"];
                    }
                    
                    //check inspection result to add new maintenance for this inspection
                    if (!inspectionResultSwitch.on) {
                        //inspection failed
                        [userDefaults setObject:[NSNumber numberWithBool:YES] forKey:IS_INSPECTION_FAILED];
                        
                        MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
                        controller.itemDetailedDict = itemDetailDict;
                        controller.theNewInspectionId = newInspectionId;
                        controller.theNewScheduleId = newScheduleId;
                        controller.beforeInspectionSavedDict = beforeInspectionSavedDict;
                        controller.beforeScheduleSavedDict = beforeScheduleSavedDict;
                        
                        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
                        navController.modalPresentationStyle = UIModalPresentationPageSheet;
                        [self presentModalViewController:navController animated:YES];
                        
                        if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                            navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
                    }
                    else {
                        if (followActionSwitch.on) {
                            //only create new maintenance
                            //if follow action
                            [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:IS_INSPECTION_FAILED];
                            
                            MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
                            controller.itemDetailedDict = itemDetailDict;
                            controller.theNewInspectionId = newInspectionId;
                            controller.theNewScheduleId = newScheduleId;
                            controller.beforeInspectionSavedDict = beforeInspectionSavedDict;
                            controller.beforeScheduleSavedDict = beforeScheduleSavedDict;
                            
                            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
                            navController.modalPresentationStyle = UIModalPresentationPageSheet;
                            [self presentModalViewController:navController animated:YES];
                            
                            if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                                navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
                        }
                        else {
                            if ([maintenanceId isEqualToString:@""] || maintenanceId == nil) {
                                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                                [dialog show];
                            }
                        }
                    }
                }
                else {
                    if ([maintenanceId isEqualToString:@""] || maintenanceId == nil) {
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                    }
                }
            }
        }
    }
}

- (void) saveMaintenanceWithSendEmail:(BOOL)sendMail {
    [self dismissPopoverController];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //set to No to reload view after tap Save.
    [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:@"isSelectDetail"];
    NSString *userId = [userDefaults objectForKey:ACCOUNT_ID];
    
    NSString *checkList = @"0";
    NSString *technicalAssessment = @"0";
    NSString *report = @"0";
    NSString *workRequest = @"0";
    NSString *costing   = @"FSR:0";
    NSString *approval  = @"0";
    NSString *epo = @"0";
    NSString *rap = @"0";
    NSString *coc = @"0";
    NSString *gr    = @"0";
    NSString *invoice = @"0";
    NSString *eto = @"0";
    NSString *startDate = @"";
    
    //get all objects in section 1 and set value
    for (int i=0;i < [mainArray count];i++) {
        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
        int objectType = [[dict objectForKey:@"objectType"] intValue];
        
        if (objectType == filter_inspection) {
            //validate type of requirement
            if ([[dict objectForKey:@"objectValue"] isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.type-of-requirement-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
        }
        else if (objectType == filter_start_date) {
            startDate = [dict objectForKey:@"objectValue"];
            if ([startDate isEqualToString:@""] || startDate == nil) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.start-date-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
        }
        else if (objectType == filter_person_in_charge) {
            NSString *personInCharge = [dict objectForKey:@"objectValue"];
            if ([personInCharge isEqualToString:[dictLanguage objectForKey:@"schedule.title-select-liaison"]] ||  [personInCharge isEqualToString:@""] || personInCharge == nil) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.person-in-charge-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
        }
        else if (objectType == m_Checklist)
            checkList = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        else if (objectType == m_Technical_Assessment) {
            technicalAssessment = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_Report) {
            report = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_Work_Request) {
            workRequest = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_Costing) {
            //costing will save to value: FSR:0 (FSR/NonFSR:costing)
            costing = [dict objectForKey:@"objectValue"];
        }
        else if (objectType == m_Approval) {
            approval = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_EPO) {
            epo = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_RAP) {
            rap = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_COC) {
            coc = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_GR) {
            gr = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_Invoice) {
            invoice = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
        else if (objectType == m_ETO) {
            eto = [NSString stringWithFormat:@"%d",[[dict objectForKey:@"objectValue"] intValue]];
        }
    }
    
    //        NSDate *today = [NSDate date];
    //        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //        NSString *todayStr = [dateFormatter stringFromDate:today];
    
    NSString *maintenanceTypeIdStr = [itemDetailDict objectForKey:@"maintenanceTypeId"] == Nil ? @"" : [itemDetailDict objectForKey:@"maintenanceTypeId"];
    
    NSString *categoryProgram = [dictLanguage objectForKey:@"maintenance-mgmt.service-type.maintenance"];
    
    if (!isEdit) {
        //firstly, we create new schedule for this maintenance, then assign the _id of this schedule for Maintenance document
        //init inputMaintenanceDict
        [inputMaintenanceDict setObject:checkList forKey:@"checkList"];
        [inputMaintenanceDict setObject:technicalAssessment forKey:@"technicalAssessment"];
        [inputMaintenanceDict setObject:report forKey:@"report"];
        [inputMaintenanceDict setObject:workRequest forKey:@"workRequest"];
        [inputMaintenanceDict setObject:costing forKey:@"costing"];
        [inputMaintenanceDict setObject:approval forKey:@"approval"];
        [inputMaintenanceDict setObject:epo forKey:@"epo"];
        [inputMaintenanceDict setObject:rap forKey:@"rap"];
        [inputMaintenanceDict setObject:coc forKey:@"coc"];
        [inputMaintenanceDict setObject:gr forKey:@"gr"];
        [inputMaintenanceDict setObject:invoice forKey:@"invoice"];
        [inputMaintenanceDict setObject:eto forKey:@"eto"];
        [inputMaintenanceDict setObject:[itemDetailDict objectForKey:@"itemId"] forKey:@"itemId"];
        [inputMaintenanceDict setObject:maintenanceTypeIdStr forKey:@"maintenanceTypeId"];
        [inputMaintenanceDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
        [inputMaintenanceDict setObject:[NSNumber numberWithInt:itemType] forKey:@"itemType"];
        [inputMaintenanceDict setObject:[NSString stringWithFormat:@"%d",UPCOMING] forKey:@"status"];
        [inputMaintenanceDict setObject:[NSNumber numberWithBool:workCompleteSwitch.on] forKey:@"workComplete"];
        
        //create new scheduling
        NSMutableDictionary *dictSchedule = [NSMutableDictionary dictionaryWithObjectsAndKeys:kScheduleDocType,@"Table",userId,@"userId",categoryProgram,@"scheduleCategory",[itemDetailDict objectForKey:@"camp"],@"camp",[itemDetailDict objectForKey:@"service"],@"service",[itemDetailDict objectForKey:@"unit"],@"unit",[itemDetailDict objectForKey:@"building"],@"building",[itemDetailDict objectForKey:@"floor"],@"floor",[itemDetailDict objectForKey:@"item_name"],@"room",[NSNumber numberWithInt:1],@"typeRequirement",startDate,@"startDate",@"",@"lastDone",@"",@"lastUpdate",personInChargeDict,@"personInCharge",@"",@"reMark",maintenanceTypeIdStr,@"maintenanceTypeId",[ApplicationDelegate getMaintenanceName:[maintenanceTypeIdStr intValue]],@"maintenanceType",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated",[NSNumber numberWithInt:itemType],@"itemType",[NSNumber numberWithInt:Maintenance],@"categoryId",[NSNumber numberWithBool:NO],@"wasRead",[itemDetailDict objectForKey:@"_id"],@"itemId",[typeRequirementDict objectForKey:@"index"],@"categoryTypeId",[typeRequirementDict objectForKey:@"filterName"],@"categoryType",nil];
        
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:dictSchedule error:&error];
        if (!error) {
            //success
            NSString *scheduleId = [dictSchedule objectForKey:@"_id"];
            
            //update scheduleId for maintenance
            [inputMaintenanceDict setObject:scheduleId forKey:@"scheduleId"];
            
            NSError *error;
            
            //check if select add new Inspection, then we add new inspection and maintenance
            int currentSelectedServiceType = [[userDefaults objectForKey:SELECTED_SERVICE_TYPE] intValue];
            if (currentSelectedServiceType == Inspection) {
                if (inputInspectionDict != nil) {
                    [inputInspectionDict setObject:scheduleId forKey:@"scheduleId"];
                    NSMutableDictionary *inspectionDict = inputInspectionDict;
                    
                    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inspectionDict error:&error];
                    if (!error) {
                        //update inspectionId for scheduleDoc
                        [dictSchedule setObject:[inspectionDict objectForKey:@"_id"] forKey:@"inspectionId"];
                        
                        //update new maintenance for this inspection
                        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inputMaintenanceDict error:&error];
                        
                        if (!error) {
                            //update maintenanceId for scheduleDoc
                            [dictSchedule setObject:[inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
                            
                            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictSchedule error:&error];
                            //success
                            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-maintenance.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                            [dialog show];
                            
                            //check workComplete to add new Maintenance and new inspection
                            if (workCompleteSwitch.on) {
                                //check maintenance type, add new with some maintenance has type of requirement
                                
                                //add new inspection
                                NSMutableDictionary *newInspectionDict = [inputInspectionDict mutableCopy];
                                [newInspectionDict removeObjectForKey:@"_id"];
                                [newInspectionDict removeObjectForKey:@"_rev"];
                                
                                [newInspectionDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                                
                                NSMutableDictionary *newInspectionScheduleDict = [dictSchedule mutableCopy];
                                [newInspectionScheduleDict removeObjectForKey:@"_id"];
                                [newInspectionScheduleDict removeObjectForKey:@"_rev"];
                                
                                [newInspectionDict setObject:[NSNumber numberWithInteger:UPCOMING] forKey:@"status"];
                                
                                //set last done (of schedule) = previous start date
                                [newInspectionDict setObject:startDate forKey:@"lastUpdate"];
                                [newInspectionScheduleDict setObject:startDate forKey:@"lastUpdate"];
                                //calculate the new next done
                                
                                int typeRequirementId = [[newInspectionScheduleDict objectForKey:@"categoryTypeId"] intValue];
                                NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                                
                                NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                                [newInspectionDict setObject:lastDate forKey:@"startDate"];
                                
                                [newInspectionScheduleDict setObject:lastDate forKey:@"startDate"];
                                [newInspectionScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                
                                //create new schedule
                                [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newInspectionScheduleDict error:&error];
                                if (!error) {
                                    [newInspectionDict setObject:[newInspectionScheduleDict objectForKey:@"_id"] forKey:@"scheduleId"];
                                    //add new maintenance
                                    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newInspectionDict error:&error];
                                }
                                
                                switch (maintenanceTypeId) {
                                    case CM_Above_Cost_Cap:
                                    case CM_Not_Under_PMWS:
                                    case New_Works_Above_70:
                                    case New_Works_Below_70:
                                        break;
                                    default:
                                    {
                                        NSMutableDictionary *newMaintenanceDict = [inputMaintenanceDict mutableCopy];
                                        [newMaintenanceDict removeObjectForKey:@"_id"];
                                        [newMaintenanceDict removeObjectForKey:@"_rev"];
                                        
                                        [newMaintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                                        
                                        NSMutableDictionary *newScheduleDict = [dictSchedule mutableCopy];
                                        [newScheduleDict removeObjectForKey:@"_id"];
                                        [newScheduleDict removeObjectForKey:@"_rev"];
                                        
                                        [newMaintenanceDict setObject:[NSNumber numberWithInteger:UPCOMING] forKey:@"status"];
                                        
                                        //set last done (of schedule) = previous start date
                                        [newMaintenanceDict setObject:startDate forKey:@"lastUpdate"];
                                        [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                                        //calculate the new next done
                                        
                                        int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                                        NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                                        
                                        NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                                        [newMaintenanceDict setObject:lastDate forKey:@"startDate"];
                                        [newScheduleDict setObject:lastDate forKey:@"startDate"];
                                        [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                        
                                        //create new schedule
                                        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                                        if (!error) {
                                            [newMaintenanceDict setObject:[newScheduleDict objectForKey:@"_id"] forKey:@"scheduleId"];
                                            //add new maintenance
                                            [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newMaintenanceDict error:&error];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else {
                    //trường hợp đã có Inspection, nhưng set result = NO
                    //add new maintenance cho inspection này, ở đây luôn tạo mới 1 maintenance, nếu back lại thị sẽ xoá maintenance này đi.
                    //update new maintenance for this inspection
                    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inputMaintenanceDict error:&error];
                    
                    if (!error) {
                        //update maintenanceId for scheduleDoc
                        [dictSchedule setObject:[inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
                        
                        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictSchedule error:&error];
                        //success
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-maintenance.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        
                        //check workComplete to add new Maintenance
                        if (workCompleteSwitch.on) {
                            //check maintenance type, add new with some maintenance has type of requirement
                            switch (maintenanceTypeId) {
                                case CM_Above_Cost_Cap:
                                case CM_Not_Under_PMWS:
                                case New_Works_Above_70:
                                case New_Works_Below_70:
                                    break;
                                default:
                                {
                                    NSMutableDictionary *newMaintenanceDict = [inputMaintenanceDict mutableCopy];
                                    [newMaintenanceDict removeObjectForKey:@"_id"];
                                    [newMaintenanceDict removeObjectForKey:@"_rev"];
                                    
                                    [newMaintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                                    
                                    NSMutableDictionary *newScheduleDict = [dictSchedule mutableCopy];
                                    [newScheduleDict removeObjectForKey:@"_id"];
                                    [newScheduleDict removeObjectForKey:@"_rev"];
                                    
                                    [newMaintenanceDict setObject:[NSNumber numberWithInteger:UPCOMING] forKey:@"status"];
                                    
                                    //set last done (of schedule) = previous start date
                                    [newMaintenanceDict setObject:startDate forKey:@"lastUpdate"];
                                    [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                                    //calculate the new next done
                                    
                                    int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                                    NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                                    
                                    NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                                    [newMaintenanceDict setObject:lastDate forKey:@"startDate"];
                                    [newScheduleDict setObject:lastDate forKey:@"startDate"];
                                    [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                    
                                    //create new schedule
                                    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                                    if (!error) {
                                        [newMaintenanceDict setObject:[newScheduleDict objectForKey:@"_id"] forKey:@"scheduleId"];
                                        //add new maintenance
                                        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newMaintenanceDict error:&error];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else {
                //only add new maintenance
                //update new maintenance for this inspection
                [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:inputMaintenanceDict error:&error];
                if (!error) {
                    //update maintenanceId for scheduleDoc
                    [dictSchedule setObject:[inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
                    
                    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictSchedule error:&error];
                    //success
                    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:Nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-maintenance.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                    [dialog show];
                    
                    //check workComplete to add new Maintenance
                    if (workCompleteSwitch.on) {
                        //check maintenance type, add new with some maintenance has type of requirement
                        switch (maintenanceTypeId) {
                            case CM_Above_Cost_Cap:
                            case CM_Not_Under_PMWS:
                            case New_Works_Above_70:
                            case New_Works_Below_70:
                                break;
                            default:
                            {
                                NSMutableDictionary *newMaintenanceDict = [inputMaintenanceDict mutableCopy];
                                [newMaintenanceDict removeObjectForKey:@"_id"];
                                [newMaintenanceDict removeObjectForKey:@"_rev"];
                                
                                [newMaintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                                
                                NSMutableDictionary *newScheduleDict = [dictSchedule mutableCopy];
                                [newScheduleDict removeObjectForKey:@"_id"];
                                [newScheduleDict removeObjectForKey:@"_rev"];
                                
                                [newMaintenanceDict setObject:[NSNumber numberWithInteger:UPCOMING] forKey:@"status"];
                                
                                //set last done (of schedule) = previous start date
                                [newMaintenanceDict setObject:startDate forKey:@"lastUpdate"];
                                [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                                //calculate the new next done
                                
                                int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                                NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                                
                                NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                                [newMaintenanceDict setObject:lastDate forKey:@"startDate"];
                                [newScheduleDict setObject:lastDate forKey:@"startDate"];
                                [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                                
                                //create new schedule
                                [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                                if (!error) {
                                    [newMaintenanceDict setObject:[newScheduleDict objectForKey:@"_id"] forKey:@"scheduleId"];
                                    //add new maintenance
                                    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newMaintenanceDict error:&error];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    else {
        
        //check permisson edit
        NSMutableDictionary *maintenancePermissionDict = [userDefaults objectForKey:MAINTENANCE_PERMISSION];
        NSMutableDictionary *permissionDict = [maintenancePermissionDict objectForKey:@"maintenance"];
        
        BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
        if (!isEditable) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
        //update status for this maintenance
        CBLDocument *maintenanceDoc = [CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"_id"]];
        NSMutableDictionary *maintenanceDict = [maintenanceDoc.properties mutableCopy];
        
        [maintenanceDict setObject:checkList forKey:@"checkList"];
        [maintenanceDict setObject:technicalAssessment forKey:@"technicalAssessment"];
        [maintenanceDict setObject:report forKey:@"report"];
        [maintenanceDict setObject:workRequest forKey:@"workRequest"];
        [maintenanceDict setObject:costing forKey:@"costing"];
        [maintenanceDict setObject:approval forKey:@"approval"];
        [maintenanceDict setObject:epo forKey:@"epo"];
        [maintenanceDict setObject:rap forKey:@"rap"];
        [maintenanceDict setObject:coc forKey:@"coc"];
        [maintenanceDict setObject:gr forKey:@"gr"];
        [maintenanceDict setObject:invoice forKey:@"invoice"];
        [maintenanceDict setObject:eto forKey:@"eto"];
        
        [maintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"wasRead"];
        [maintenanceDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
        [maintenanceDict setObject:[NSNumber numberWithBool:workCompleteSwitch.on] forKey:@"workComplete"];
        if (!workCompleteSwitch.on)
            [maintenanceDict setObject:[NSNumber numberWithInt:IN_PROCESS] forKey:@"status"];
        else {
            [maintenanceDict setObject:[NSNumber numberWithInt:COMPLETED] forKey:@"status"];
        }
        
        //update status for maintenance
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:maintenanceDict error:&error];
        if (!error) {
            //get scheduleDoc of this maintenance and update schedule
            CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:[maintenanceDict objectForKey:@"scheduleId"]];
            NSMutableDictionary *_scheduleDict = [scheduleDoc.properties mutableCopy];
            
            [_scheduleDict setObject:startDate forKey:@"startDate"];
            
            @try {
                [_scheduleDict setObject:[typeRequirementDict objectForKey:@"index"] forKey:@"categoryTypeId"];
                [_scheduleDict setObject:[typeRequirementDict objectForKey:@"filterName"] forKey:@"categoryType"];
            }
            @catch (NSException *e) {
                NSLog(@"handleRightCornerEvent = %@",e);
            }
            
            [_scheduleDict setObject:personInChargeDict forKey:@"personInCharge"];
            [_scheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
            [_scheduleDict setObject:[NSNumber numberWithBool:NO] forKey:@"wasRead"];
            
            //check status of this maintenance, if completed, we add one more maintenance and update last done for this schedule
            int status = [[maintenanceDict objectForKey:@"status"] intValue];
            if (status == COMPLETED) {
                switch (maintenanceTypeId) {
                    case CM_Above_Cost_Cap:
                    case CM_Not_Under_PMWS:
                    case New_Works_Above_70:
                    case New_Works_Below_70:
                        break;
                    default:
                    {
                        //create new maintenance and new schedule
                        NSMutableDictionary *newScheduleDict = [_scheduleDict mutableCopy];
                        [newScheduleDict removeObjectForKey:@"_rev"];
                        [newScheduleDict removeObjectForKey:@"_id"];
                        
                        NSMutableDictionary *newMaintenanceDict = [maintenanceDict mutableCopy];
                        [newMaintenanceDict removeObjectForKey:@"_rev"];
                        [newMaintenanceDict removeObjectForKey:@"_id"];
                        
                        [newMaintenanceDict setObject:[NSNumber numberWithInteger:UPCOMING] forKey:@"status"];
                        
                        //set last done (of schedule) = previous start date
                        [newMaintenanceDict setObject:startDate forKey:@"lastUpdate"];
                        [newScheduleDict setObject:startDate forKey:@"lastUpdate"];
                        //calculate the new next done
                        
                        int typeRequirementId = [[newScheduleDict objectForKey:@"categoryTypeId"] intValue];
                        NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirementId];
                        
                        NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
                        [newMaintenanceDict setObject:lastDate forKey:@"startDate"];
                        [newScheduleDict setObject:lastDate forKey:@"startDate"];
                        [newScheduleDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
                        
                        //reset workComplete to OFF for new maintenance
                        [newMaintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"workComplete"];
                        
                        //create new schedule
                        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newScheduleDict error:&error];
                        if (!error) {
                            [newMaintenanceDict setObject:[newScheduleDict objectForKey:@"_id"] forKey:@"scheduleId"];
                            //add new maintenance
                            [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:newMaintenanceDict error:&error];
                        }
                        
                        break;
                    }
                }
            }
            
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:_scheduleDict error:&error];
            if (!error) {
                NSLog(@"update schedule successed");
            }
            else {
                NSLog(@"update schedule failed");
            }
            
            //update success
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:[dictLanguage objectForKey:@"maintenance-mgmt.add-maintenance.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
        }
    }
    
    if (sendMail) {
        //send mail
        [self performSelectorInBackground:@selector(sendEmailMaintenance) withObject:nil];
    }
}

- (void) sendEmailMaintenance {
    /*
     1: name : (tên họ), 2: itemName:  (tên item) , 3: itemID : (id của item), 4: email (email để gởi), 5: user (username), 6: time ( thời gian), 7: date (ngày tháng năm)
     (14:43) Hung Do Huu: link service: /api/maintenance/sendEmailMaintanance
     */

    NSMutableDictionary *itemDict;
    NSMutableDictionary *scheduleDict;
    
    if (isEdit) {
        itemDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"itemId"]].properties;
        scheduleDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"scheduleId"]].properties;
    }
    else {
        itemDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:[inputMaintenanceDict objectForKey:@"itemId"]].properties;
        scheduleDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:[inputMaintenanceDict objectForKey:@"scheduleId"]].properties;
    }
    
//    NSLog(@"itemDict = %@",itemDict);
//    NSLog(@"scheduleDict = %@",scheduleDict);
    
    NSString *personInChargeName  = [[scheduleDict objectForKey:@"personInCharge"] objectForKey:@"filterName"];
    NSString *personInChargeEmail = [[scheduleDict objectForKey:@"personInCharge"] objectForKey:@"email"];
    NSString *itemName = [itemDict objectForKey:@"item_name"];
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:ACCOUNT_NAME];
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *todayStr = [dateFormatter stringFromDate:today];
    NSArray *tmpArray = [todayStr componentsSeparatedByString:@" "];
    NSString *date = [tmpArray objectAtIndex:0];
    NSString *time = [tmpArray objectAtIndex:1];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:personInChargeName,@"name",itemName,@"itemName",[itemDict objectForKey:@"_id"],@"itemID",personInChargeEmail,@"email",username,@"user",time,@"time",date,@"date", nil];
    [[FMSServerAPI shareClient] sendEmailMaintenance:params successs:^(NSMutableDictionary *success) {
        NSLog(@"send mail success = %@",success);
    } failure:^(NSError *error) {
        NSLog(@"send mail fail = %@",error);
    }];
}

- (void) handleCostingRequest:(int)_isApproved {
    int tmpStatus;
    NSString *msg = @"";
    if (_isApproved) {
        //set maintenance status to Approve Costing
        tmpStatus = COSTING_APPROVED;
        msg = [dictLanguage objectForKey:@"maintenance-mgmt.detail.approve-success-message"];
    }
    else {
        //set maintenance status to Reject Costing
        tmpStatus = REJECT_QUOTATION;
        msg = [dictLanguage objectForKey:@"maintenance-mgmt.detail.reject-success-message"];
    }
    
    CBLDocument *maintenanceDoc = [CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"_id"]];
    NSMutableDictionary *maintenanceDict = [maintenanceDoc.properties mutableCopy];
    [maintenanceDict setObject:[NSNumber numberWithBool:NO] forKey:@"wasRead"];
    [maintenanceDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
    [maintenanceDict setObject:[NSNumber numberWithInt:tmpStatus] forKey:@"status"];
    
    //update status for maintenance
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:maintenanceDict error:&error];
    if (!error) {
        //update success
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
    }
}

- (IBAction)switchSegment:(UIButton *)sender {
    if (isEdit) {
        currentSelectedIndex = sender.tag;
        int result = [[itemDetailDict objectForKey:@"result"] intValue];
        if (!result) {
            [mainArray removeAllObjects];
            
            if (currentSelectedIndex == Maintenance) {
                [_btnMaintenance setSelected:YES];
                [_btnInspection setSelected:NO];
                
                //if Inspection failed, in Inspection object has a field to point Maintenance object
                //init temporaty data for Maintenance object for this Inspection
                NSString *maintenanceId = [itemDetailDict objectForKey:@"maintenanceId"];
                CBLDocument *maintenanceDoc = [CouchBaseLiteLib getDocumentById:maintenanceId];
                NSMutableArray *maintenanceDataArray = [maintenanceDoc.properties objectForKey:@"itemData"];
                
                maintenanceTypeId = [[maintenanceDoc propertyForKey:@"maintenanceTypeId"] intValue];
                _lbMainTitle.text = [ApplicationDelegate getMaintenanceName:maintenanceTypeId];
                
                //init data for maintenance
                switch (maintenanceTypeId)
                {
                    case PM:
                    case CM:
                    {
                        NSString *labelTitle[] = {
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
                        };
                        NSString *objectType[] = {
                            [NSString stringWithFormat:@"%d",m_Checklist],
                            [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                            [NSString stringWithFormat:@"%d",m_Report],
                            [NSString stringWithFormat:@"%d",m_RAP],
                            [NSString stringWithFormat:@"%d",m_COC],
                        };
                        //get value from maintenanceDataArray
                        NSMutableArray *objectValue = [NSMutableArray arrayWithCapacity:1];
                        for (int i=0;i < [maintenanceDataArray count];i++) {
                            NSMutableDictionary *tmpDict = [maintenanceDataArray objectAtIndex:i];
                            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                            switch (objectType) {
                                case m_Checklist:
                                case m_Technical_Assessment:
                                case m_Report:
                                case m_RAP:
                                case m_COC:
                                    [objectValue addObject:[NSString stringWithFormat:@"%@",[tmpDict objectForKey:@"objectValue"]]];
                                    break;
                                default:
                                    break;
                            }
                        }
                       
                        for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                            [mainArray addObject:dict];
                        }
                        
                        break;
                    }
                    case PMS:
                    case CM_Above_Cost_Cap:
                    case CM_Not_Under_PMWS:
                    {
                        NSString *labelTitle[] = {
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.work-request"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.costing"],
//                            [dictLanguage objectForKey:@"maintenance-mgmt.action.approval"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.epo"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.gr"],
                        };
                        NSString *objectType[] = {
                            [NSString stringWithFormat:@"%d",m_Checklist],
                            [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                            [NSString stringWithFormat:@"%d",m_Report],
                            [NSString stringWithFormat:@"%d",m_Work_Request],
                            [NSString stringWithFormat:@"%d",m_Costing],
//                            [NSString stringWithFormat:@"%d",m_Approval],
                            [NSString stringWithFormat:@"%d",m_EPO],
                            [NSString stringWithFormat:@"%d",m_RAP],
                            [NSString stringWithFormat:@"%d",m_COC],
                            [NSString stringWithFormat:@"%d",m_GR]
                        };
                        //get value from maintenanceDataArray
                        NSMutableArray *objectValue = [NSMutableArray arrayWithCapacity:1];
                        for (int i=0;i < [maintenanceDataArray count];i++) {
                            NSMutableDictionary *tmpDict = [maintenanceDataArray objectAtIndex:i];
                            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                            switch (objectType) {
                                case m_Checklist:
                                case m_Technical_Assessment:
                                case m_Report:
                                case m_Work_Request:
                                case m_Costing:
//                                case m_Approval:
                                case m_EPO:
                                case m_RAP:
                                case m_COC:
                                case m_GR:
                                    [objectValue addObject:[NSString stringWithFormat:@"%@",[tmpDict objectForKey:@"objectValue"]]];
                                    break;
                                default:
                                    break;
                            }
                        }
                        for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                            [mainArray addObject:dict];
                        }
                        break;
                    }
                    case New_Works_Above_70:
                    case New_Works_Below_70:
                    {
                        NSString *labelTitle[] = {
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.work-request"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.costing"],
//                            [dictLanguage objectForKey:@"maintenance-mgmt.action.approval"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.epo"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.gr"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.invoice"],
                            [dictLanguage objectForKey:@"maintenance-mgmt.action.eto"],
                        };
                        NSString *objectType[] = {
                            [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                            [NSString stringWithFormat:@"%d",m_Report],
                            [NSString stringWithFormat:@"%d",m_Work_Request],
                            [NSString stringWithFormat:@"%d",m_Costing],
//                            [NSString stringWithFormat:@"%d",m_Approval],
                            [NSString stringWithFormat:@"%d",m_EPO],
                            [NSString stringWithFormat:@"%d",m_RAP],
                            [NSString stringWithFormat:@"%d",m_COC],
                            [NSString stringWithFormat:@"%d",m_GR],
                            [NSString stringWithFormat:@"%d",m_Invoice],
                            [NSString stringWithFormat:@"%d",m_ETO],
                        };
                        
                        //get value from maintenanceDataArray
                        NSMutableArray *objectValue = [NSMutableArray arrayWithCapacity:1];
                        for (int i=0;i < [maintenanceDataArray count];i++) {
                            NSMutableDictionary *tmpDict = [maintenanceDataArray objectAtIndex:i];
                            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                            switch (objectType) {
                                case m_Technical_Assessment:
                                case m_Report:
                                case m_Work_Request:
                                case m_Costing:
//                                case m_Approval:
                                case m_EPO:
                                case m_RAP:
                                case m_COC:
                                case m_GR:
                                case m_Invoice:
                                case m_ETO:
                                    [objectValue addObject:[NSString stringWithFormat:@"%@",[tmpDict objectForKey:@"objectValue"]]];
                                    break;
                                default:
                                    break;
                            }
                        }
                        for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                            [mainArray addObject:dict];
                        }
                        break;
                    }
                }
            }
            else {
                [_btnMaintenance setSelected:NO];
                [_btnInspection setSelected:YES];
                _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"];
                //recreate data for Inspection
                NSString *lbTitle[] = {
                    [dictLanguage objectForKey:@"schedule.title-ending-date"],
                    [dictLanguage objectForKey:@"schedule.title-starting-date"],
                    [dictLanguage objectForKey:@"schedule.title-person-in-charge"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                    [dictLanguage objectForKey:@"maintenance-mgmt.action.inspection-result"],
                };
                
                NSString *objectType[] = {
                    [NSString stringWithFormat:@"%d",filter_end_date],
                    [NSString stringWithFormat:@"%d",filter_start_date], //textfield
                    [NSString stringWithFormat:@"%d",filter_person_in_charge],
                    [NSString stringWithFormat:@"%d",m_Checklist],
                    [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                    [NSString stringWithFormat:@"%d",m_Report],
                    [NSString stringWithFormat:@"%d",m_Inspection_Result],
                };

                //if view detail Inspection from Maintenance Mgmt
                NSString *objectValue[] = {
                    [itemDetailDict objectForKey:@"lastUpdate"],
                    [itemDetailDict objectForKey:@"startDate"],
                    [itemDetailDict objectForKey:@"personInCharge"],
                    [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"checkList"] intValue]],
                    [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"technicalAssessment"] intValue]],
                    [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"report"] intValue]],
                    [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"result"] intValue]],
                };
                
                for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            
            [_mainTableView reloadData];
        }
    }
}

- (void) initNewControllerBeforeConfirmMaintenance:(NSMutableDictionary*)_dict itemDetailedDict:(NSMutableDictionary*)_itemDetailedDict {
    MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Maintenance];
    controller.itemDetailDict = _itemDetailedDict;
    controller.inputInspectionDict = inputInspectionDict;
    controller.itemType = itemType;
    [self.navigationController pushViewController:controller animated:NO];

    [self performSelector:@selector(delayAfterInit:) withObject:_dict afterDelay:0.5];
}

- (void) delayAfterInit:(NSMutableDictionary*)_dict {
    MaintenanceDetailedViewController *controller = [self.navigationController.viewControllers lastObject];
    
    NSMutableDictionary *tmpDict = [controller.itemDetailDict mutableCopy];
    [tmpDict setObject:[_dict objectForKey:@"itemType"] forKey:@"maintenanceTypeId"];
    [controller confirmMaintenanceType:_dict itemDetailedDict:tmpDict];
}

//confirm to choose Maintenance Type from previous view
- (void) confirmMaintenanceType:(NSMutableDictionary*)_maintenanceTypeDict itemDetailedDict:(NSMutableDictionary*)_itemDetailedDict {

    itemDetailDict = _itemDetailedDict;
    
    maintenanceTypeId = [[_maintenanceTypeDict objectForKey:@"itemType"] intValue];
    _lbMainTitle.text = [_maintenanceTypeDict objectForKey:@"itemName"];
    
    [_btnInspection setSelected:NO];
    [_btnMaintenance setSelected:YES];

    //init data for schedule
    NSString *lbTitle[] = {
        [dictLanguage objectForKey:@"schedule.title-type-requirement"],
        [dictLanguage objectForKey:@"schedule.title-last-done"],
        [dictLanguage objectForKey:@"schedule.title-starting-date"],
        [dictLanguage objectForKey:@"schedule.title-person-in-charge"],
    };
    
    NSString *objectType[] = {
        [NSString stringWithFormat:@"%d",filter_inspection],
        [NSString stringWithFormat:@"%d",filter_end_date], // last done
        [NSString stringWithFormat:@"%d",filter_start_date], //textfield
        [NSString stringWithFormat:@"%d",filter_person_in_charge],
    };
    
    if (isEdit) {
        //get scheduleDoc from this maintenance
        CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"scheduleId"]];
        NSMutableDictionary *scheduleDict = [scheduleDoc.properties mutableCopy];
        
        personInChargeDict = [scheduleDict objectForKey:@"personInCharge"];
        
        typeRequirementDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[scheduleDict objectForKey:@"categoryTypeId"],@"index",[scheduleDict objectForKey:@"categoryType"],@"filterName", nil];
        
        NSString *objectValue[] = {
            [typeRequirementDict objectForKey:@"filterName"],
            [scheduleDict objectForKey:@"lastUpdate"],
            [scheduleDict objectForKey:@"startDate"],
            [personInChargeDict objectForKey:@"filterName"],
        };
        for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
            //only add typeRequirement for PM,CM,PMS
            switch (maintenanceTypeId) {
                case CM_Above_Cost_Cap:
                case CM_Not_Under_PMWS:
                case New_Works_Above_70:
                case New_Works_Below_70:
                    if (i==0)
                        continue;
                    break;
                default:
                    break;
            }
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
            [mainArray addObject:dict];
        }
    }
    else {
        NSString *itemTable = [itemDetailDict objectForKey:@"Table"];
        [itemInfoArray removeAllObjects];
        if ([itemTable isEqualToString:FacilityMgmtDoc]) {
            //            itemType = Facility_Type;
            //organize the item data array
            NSString *itemTitle[] = {
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.description"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.system"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.location"]],
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Name],
                [NSString stringWithFormat:@"%d",m_Item_Description],
                [NSString stringWithFormat:@"%d",m_Item_System],
                [NSString stringWithFormat:@"%d",m_Item_Location],
            };
            
            NSString *itemValue[] = {
                [itemDetailDict objectForKey:@"item_name"],
                [itemDetailDict objectForKey:@"description"],
                [itemDetailDict objectForKey:@"system"],
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDetailDict objectForKey:@"room"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }
        else {
            //            itemType = Building_Type;
            //organize the item data array
            NSString *itemTitle[] = {
                @""
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Label]
            };
            
            NSString *itemValue[] = {
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDetailDict objectForKey:@"item_name"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }

        //when add new maintenance, we create a temporary maintenance first for eForm purpose, to get ID of this maintenance
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *userId = [userDefaults objectForKey:ACCOUNT_ID];
        inputMaintenanceDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:MaintenanceDoc,@"Table",userId,@"userId", nil];
        
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:inputMaintenanceDict error:&error];
        if (!error) {
            NSLog(@"create temporary maintenance success");
        }
        
        NSString *objectValue[] = {
            [dictLanguage objectForKey:@"schedule.title-select"],
            @"",
            @"",
            [dictLanguage objectForKey:@"schedule.title-select-liaison"],
        };
        for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
            //only add typeRequirement for PM,CM,PMS
            switch (maintenanceTypeId) {
                case CM_Above_Cost_Cap:
                case CM_Not_Under_PMWS:
                case New_Works_Above_70:
                case New_Works_Below_70:
                    if (i==0)
                        continue;
                    break;
                default:
                    break;
            }
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
            [mainArray addObject:dict];
        }
    }
    //init data for all MaintenanceType

    switch (maintenanceTypeId)
    {
        case PM:
        case CM:
        {
            NSString *labelTitle[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
            };
            NSString *objectType[] = {
                [NSString stringWithFormat:@"%d",m_Checklist],
                [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                [NSString stringWithFormat:@"%d",m_Report],
                [NSString stringWithFormat:@"%d",m_RAP],
                [NSString stringWithFormat:@"%d",m_COC],
            };
            
            if (!isEdit) {
                //we init data when add new
                NSString *objectValue[] = {
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1"
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            else {
                NSString *objectValue[] = {
                    [itemDetailDict objectForKey:@"checkList"],
                    [itemDetailDict objectForKey:@"technicalAssessment"],
                    [itemDetailDict objectForKey:@"report"],
                    [itemDetailDict objectForKey:@"rap"],
                    [itemDetailDict objectForKey:@"coc"],
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            
            break;
        }
        case PMS:
        case CM_Above_Cost_Cap:
        case CM_Not_Under_PMWS:
        {
            NSString *labelTitle[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.work-request"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.costing"],
//                [dictLanguage objectForKey:@"maintenance-mgmt.action.approval"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.epo"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.gr"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.invoice"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.eto"],
            };
            NSString *objectType[] = {
                [NSString stringWithFormat:@"%d",m_Checklist],
                [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                [NSString stringWithFormat:@"%d",m_Report],
                [NSString stringWithFormat:@"%d",m_Work_Request],
                [NSString stringWithFormat:@"%d",m_Costing],
//                [NSString stringWithFormat:@"%d",m_Approval],
                [NSString stringWithFormat:@"%d",m_EPO],
                [NSString stringWithFormat:@"%d",m_RAP],
                [NSString stringWithFormat:@"%d",m_COC],
                [NSString stringWithFormat:@"%d",m_GR],
                [NSString stringWithFormat:@"%d",m_Invoice],
                [NSString stringWithFormat:@"%d",m_ETO],
            };
            
            if (!isEdit) {
                NSString *objectValue[] = {
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    [NSString stringWithFormat:@"FSR:1:0"], //first element is value for FSR / Non FSR | second is switch button Yes/No / Third is quotating value
//                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1"
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            else {
                NSString *objectValue[] = {
                    [itemDetailDict objectForKey:@"checkList"],
                    [itemDetailDict objectForKey:@"technicalAssessment"],
                    [itemDetailDict objectForKey:@"report"],
                    [itemDetailDict objectForKey:@"workRequest"],
                    [itemDetailDict objectForKey:@"costing"], //first element is value for FSR / Non FSR | second is switch button Yes/No / third is quotating value
//                    [itemDetailDict objectForKey:@"approval"],
                    [itemDetailDict objectForKey:@"epo"],
                    [itemDetailDict objectForKey:@"rap"],
                    [itemDetailDict objectForKey:@"coc"],
                    [itemDetailDict objectForKey:@"gr"],
                    [itemDetailDict objectForKey:@"invoice"],
                    [itemDetailDict objectForKey:@"eto"],
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            break;
        }
        case New_Works_Above_70:
        case New_Works_Below_70:
        {
            NSString *labelTitle[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.work-request"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.costing"],
//                [dictLanguage objectForKey:@"maintenance-mgmt.action.approval"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.epo"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.rap"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.coc"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.gr"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.invoice"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.eto"],
            };
            NSString *objectType[] = {
                [NSString stringWithFormat:@"%d",m_Technical_Assessment],
                [NSString stringWithFormat:@"%d",m_Report],
                [NSString stringWithFormat:@"%d",m_Work_Request],
                [NSString stringWithFormat:@"%d",m_Costing],
//                [NSString stringWithFormat:@"%d",m_Approval],
                [NSString stringWithFormat:@"%d",m_EPO],
                [NSString stringWithFormat:@"%d",m_RAP],
                [NSString stringWithFormat:@"%d",m_COC],
                [NSString stringWithFormat:@"%d",m_GR],
                [NSString stringWithFormat:@"%d",m_Invoice],
                [NSString stringWithFormat:@"%d",m_ETO],
            };
            
            if (!isEdit) {
                NSString *objectValue[] = {
                    @"1",
                    @"1",
                    @"1",
                    [NSString stringWithFormat:@"FSR:1:0"], //first element is value for FSR / Non FSR | second is switch button Yes/No / Third is quotating value
//                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1",
                    @"1"
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            else {
                NSString *objectValue[] = {
                    [itemDetailDict objectForKey:@"technicalAssessment"],
                    [itemDetailDict objectForKey:@"report"],
                    [itemDetailDict objectForKey:@"workRequest"],
                    [itemDetailDict objectForKey:@"costing"], //first element is value for FSR / Non FSR | second is switch button Yes/No | Third is quotation value
//                    [itemDetailDict objectForKey:@"approval"],
                    [itemDetailDict objectForKey:@"epo"],
                    [itemDetailDict objectForKey:@"rap"],
                    [itemDetailDict objectForKey:@"coc"],
                    [itemDetailDict objectForKey:@"gr"],
                    [itemDetailDict objectForKey:@"invoice"],
                    [itemDetailDict objectForKey:@"eto"],
                };
                for (int i=0;i < sizeof(labelTitle)/sizeof(labelTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:labelTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                    [mainArray addObject:dict];
                }
            }
            break;
        }
    }
    [_mainTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationController.navigationBar.hidden = YES;
    
    _mainTitleContainerView.frame = CGRectMake(-1, -1, 1028, 45);
    _btnBack.frame = CGRectMake(0, 0, 44, 44);
    _btnRightCorner.frame = CGRectMake(980, 0, 44, 44);
    
    _mainTitleContainerView.layer.borderColor = APPLE_BLUE_COLOR.CGColor;
    _mainTitleContainerView.layer.borderWidth = 1;
    
    _mainTableView.separatorColor = [UIColor clearColor];
    
    _lbMainTitle.text = [dictLanguage objectForKey:@"building-mgmt.item.maintenance-mgmt"];
    
    //set inspection segment button
    
    //check iOS version
    _btnInspection.layer.borderWidth = 1;
    _btnInspection.layer.borderColor = [UIColor whiteColor].CGColor;
    
    _btnMaintenance.layer.borderWidth = 1;
    _btnMaintenance.layer.borderColor = [UIColor whiteColor].CGColor;
    
    [_btnInspection setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateNormal];
    [_btnInspection setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnInspection setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateSelected];
    [_btnInspection setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateSelected];
    
    //set maintenance segment button
    [_btnMaintenance setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateNormal];
    [_btnMaintenance setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnMaintenance setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateSelected];
    [_btnMaintenance setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateSelected];
    
    _btnInspection.userInteractionEnabled = _btnMaintenance.userInteractionEnabled = NO;
    
    [_mainTableView setAllowsSelection:NO];
    
    itemInfoArray = [NSMutableArray arrayWithCapacity:1];
    workStatusArray = [NSMutableArray arrayWithCapacity:1];
    
    workCompleteSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(495, 5, 102, 30)];
    workCompleteSwitch.tag = m_Work_Complete;
    [workCompleteSwitch addTarget:self action:@selector(valueChangeWorkComplete:) forControlEvents:UIControlEventValueChanged];
    workCompleteSwitch.on = NO;
    
    inspectionResultSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(495, 5, 102, 30)];
    inspectionResultSwitch.tag = m_Inspection_Result;
    [inspectionResultSwitch addTarget:self action:@selector(valueChangeInspectionResult:) forControlEvents:UIControlEventValueChanged];
    inspectionResultSwitch.on = NO;
    
    followActionSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(495, 5, 102, 30)];
    followActionSwitch.tag = m_Follow_Up_Action;
    [followActionSwitch addTarget:self action:@selector(valueChangeFollowUpAction:) forControlEvents:UIControlEventValueChanged];
    followActionSwitch.on = NO;

    /***********ITEM DATA**********************/
    if ([parent isKindOfClass:[BuildingMgmtViewController class]]) {
        //add new Inspection or Maintenance
        NSString *itemTable = [itemDetailDict objectForKey:@"Table"];
        
        if ([itemTable isEqualToString:FacilityMgmtDoc]) {
//            itemType = Facility_Type;
            //organize the item data array
            NSString *itemTitle[] = {
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.description"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.system"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.location"]],
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Name],
                [NSString stringWithFormat:@"%d",m_Item_Description],
                [NSString stringWithFormat:@"%d",m_Item_System],
                [NSString stringWithFormat:@"%d",m_Item_Location],
            };
            
            NSString *itemValue[] = {
                [itemDetailDict objectForKey:@"item_name"] == nil ? [itemDetailDict objectForKey:@"name"] : [itemDetailDict objectForKey:@"item_name"],
                [itemDetailDict objectForKey:@"description"],
                [itemDetailDict objectForKey:@"system"],
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDetailDict objectForKey:@"room"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }
        else {
//            itemType = Building_Type;
            //organize the item data array
            NSString *itemTitle[] = {
                @""
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Label]
            };
            
            NSString *itemValue[] = {
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDetailDict objectForKey:@"item_name"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }
    }
    else if ([parent isKindOfClass:[DetailedItemViewController class]]) {
        if (!isEdit) {
            //add new Inspection or Maintenance
            NSString *itemTable = [itemDetailDict objectForKey:@"Table"];
            
            if ([itemTable isEqualToString:FacilityMgmtDoc]) {
                itemType = Facility_Type;
                //organize the item data array
                NSString *itemTitle[] = {
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.description"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.system"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.location"]],
                };
                
                NSString *itemTitleType[] = {
                    [NSString stringWithFormat:@"%d",m_Item_Name],
                    [NSString stringWithFormat:@"%d",m_Item_Description],
                    [NSString stringWithFormat:@"%d",m_Item_System],
                    [NSString stringWithFormat:@"%d",m_Item_Location],
                };
                
                NSString *itemValue[] = {
                    [itemDetailDict objectForKey:@"item_name"] == nil ? [itemDetailDict objectForKey:@"name"] : [itemDetailDict objectForKey:@"item_name"],
                    [itemDetailDict objectForKey:@"description"],
                    [itemDetailDict objectForKey:@"system"],
                    [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDetailDict objectForKey:@"room"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
                };
                
                for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                    [itemInfoArray addObject:dict];
                }
            }
            else {
                itemType = Building_Type;
                //organize the item data array
                NSString *itemTitle[] = {
                    @""
                };
                
                NSString *itemTitleType[] = {
                    [NSString stringWithFormat:@"%d",m_Item_Label]
                };
                
                NSString *itemName = [itemDetailDict objectForKey:@"item_name"] == nil ? [itemDetailDict objectForKey:@"roomName"] : [itemDetailDict objectForKey:@"item_name"];
                NSString *itemValue[] = {
                    [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],itemName,[dictLanguage objectForKey:@"schedule.title-floor"],[itemDetailDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDetailDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDetailDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDetailDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDetailDict objectForKey:@"service"]],
                };
                
                for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                    [itemInfoArray addObject:dict];
                }
            }
        }
        else {
            //detailed Inspection or Maintenance
            NSMutableDictionary *itemDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"itemId"]].properties;
            NSString *itemTable = [itemDict objectForKey:@"Table"];
            if ([itemTable isEqualToString:FacilityMgmtDoc]) {
                itemType = Facility_Type;
                
                //organize the item data array
                NSString *itemTitle[] = {
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.description"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.system"]],
                    [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.location"]],
                };
                
                NSString *itemTitleType[] = {
                    [NSString stringWithFormat:@"%d",m_Item_Name],
                    [NSString stringWithFormat:@"%d",m_Item_Description],
                    [NSString stringWithFormat:@"%d",m_Item_System],
                    [NSString stringWithFormat:@"%d",m_Item_Location],
                };
                
                NSString *itemValue[] = {
                    [itemDict objectForKey:@"item_name"] == nil ? [itemDict objectForKey:@"name"] : [itemDict objectForKey:@"item_name"],
                    [itemDict objectForKey:@"description"],
                    [itemDict objectForKey:@"system"],
                    [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDict objectForKey:@"room"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDict objectForKey:@"service"]],
                };
                
                for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                    [itemInfoArray addObject:dict];
                }
            }
            else {
                itemType = Building_Type;
                
                //organize the item data array
                NSString *itemTitle[] = {
                    @""
                };
                
                NSString *itemTitleType[] = {
                    [NSString stringWithFormat:@"%d",m_Item_Label]
                };
                
                NSString *itemName = [itemDict objectForKey:@"item_name"] == nil ? [itemDict objectForKey:@"roomName"] : [itemDict objectForKey:@"item_name"];
                NSString *itemValue[] = {
                    [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],itemName,[dictLanguage objectForKey:@"schedule.title-floor"],[itemDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDict objectForKey:@"service"]],
                };
                
                for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                    [itemInfoArray addObject:dict];
                }
            }
        }
    }
    else {
        //detailed Inspection or Maintenance
        NSString *itemId = [itemDetailDict objectForKey:@"itemId"] == nil ? [itemDetailDict objectForKey:@"_id"] : [itemDetailDict objectForKey:@"itemId"];
        NSMutableDictionary *itemDict = (NSMutableDictionary*)[CouchBaseLiteLib getDocumentById:itemId].properties;
        NSString *itemTable = [itemDict objectForKey:@"Table"];
        if ([itemTable isEqualToString:FacilityMgmtDoc]) {
            itemType = Facility_Type;
            
            //organize the item data array
            NSString *itemTitle[] = {
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.description"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.system"]],
                [NSString stringWithFormat:@"%@:",[dictLanguage objectForKey:@"facility.add-new-equipment.location"]],
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Name],
                [NSString stringWithFormat:@"%d",m_Item_Description],
                [NSString stringWithFormat:@"%d",m_Item_System],
                [NSString stringWithFormat:@"%d",m_Item_Location],
            };
            
            NSString *itemValue[] = {
                [itemDict objectForKey:@"item_name"] == nil ? [itemDict objectForKey:@"roomName"] : [itemDict objectForKey:@"item_name"],
                [itemDict objectForKey:@"description"],
                [itemDict objectForKey:@"system"],
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],[itemDict objectForKey:@"room"],[dictLanguage objectForKey:@"schedule.title-floor"],[itemDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }
        else {
            itemType = Building_Type;
            
            //organize the item data array
            NSString *itemTitle[] = {
                @""
            };
            
            NSString *itemTitleType[] = {
                [NSString stringWithFormat:@"%d",m_Item_Label]
            };
            
            NSString *itemName = [itemDict objectForKey:@"item_name"] == nil ? [itemDict objectForKey:@"roomName"] : [itemDict objectForKey:@"item_name"];
            NSString *itemValue[] = {
                [NSString stringWithFormat:@"%@:%@ ,%@:%@, %@:%@, %@:%@, %@:%@, %@:%@",[dictLanguage objectForKey:@"schedule.title-room"],itemName,[dictLanguage objectForKey:@"schedule.title-floor"],[itemDict objectForKey:@"floor"],[dictLanguage objectForKey:@"schedule.title-building"],[itemDict objectForKey:@"building"],[dictLanguage objectForKey:@"schedule.title-unit"],[itemDict objectForKey:@"unit"],[dictLanguage objectForKey:@"schedule.title-camp"],[itemDict objectForKey:@"camp"],[dictLanguage objectForKey:@"schedule.title-service"],[itemDict objectForKey:@"service"]],
            };
            
            for (int i=0;i < sizeof(itemTitle)/sizeof(itemTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemTitle[i],@"labelTitle",itemValue[i],@"objectValue",itemTitleType[i],@"objectType",nil];
                [itemInfoArray addObject:dict];
            }
        }
    }
    
    /**************END ITEM DATA****************/
    //check if serviceType = Inspection
    if (serviceType == Inspection) {
        _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"];
        [_btnRightCorner setBackgroundImage:[UIImage imageNamed:@"btnSave.png"] forState:UIControlStateNormal];
        [_btnInspection setSelected:YES];
        
        NSString *lbTitle[] = {
            [dictLanguage objectForKey:@"schedule.title-type-requirement"],
            [dictLanguage objectForKey:@"schedule.title-last-done"],
            [dictLanguage objectForKey:@"schedule.title-starting-date"],
            [dictLanguage objectForKey:@"schedule.title-person-in-charge"],
            [dictLanguage objectForKey:@"maintenance-mgmt.action.checklist"],
            [dictLanguage objectForKey:@"maintenance-mgmt.action.technical-assessment"],
            [dictLanguage objectForKey:@"maintenance-mgmt.action.report"],
        };
        
        NSString *objectType[] = {
            [NSString stringWithFormat:@"%d",filter_inspection],
            [NSString stringWithFormat:@"%d",filter_end_date], // last done
            [NSString stringWithFormat:@"%d",filter_start_date], //textfield
            [NSString stringWithFormat:@"%d",filter_person_in_charge],
            [NSString stringWithFormat:@"%d",m_Checklist],
            [NSString stringWithFormat:@"%d",m_Technical_Assessment],
            [NSString stringWithFormat:@"%d",m_Report],
        };
        
        if (isEdit) {
#pragma mark View Detail Inspection
//            _btnRightCorner.hidden = YES;
//            _btnInspection.userInteractionEnabled = _btnMaintenance.userInteractionEnabled = YES;
            
            //get scheduleDoc from this maintenance
            CBLDocument *scheduleDoc = [CouchBaseLiteLib getDocumentById:[itemDetailDict objectForKey:@"scheduleId"]];
            NSMutableDictionary *scheduleDict = [scheduleDoc.properties mutableCopy];
            
            personInChargeDict = [scheduleDict objectForKey:@"personInCharge"];
            
            typeRequirementDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[scheduleDict objectForKey:@"categoryTypeId"],@"index",[scheduleDict objectForKey:@"categoryType"],@"filterName", nil];

            //if view detail Inspection from Maintenance Mgmt
            NSString *objectValue[] = {
                [typeRequirementDict objectForKey:@"filterName"],
                [scheduleDict objectForKey:@"lastUpdate"],
                [scheduleDict objectForKey:@"startDate"],
                [personInChargeDict objectForKey:@"filterName"],
                [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"checkList"] intValue]],
                [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"technicalAssessment"] intValue]],
                [NSString stringWithFormat:@"%d",[[itemDetailDict objectForKey:@"report"] intValue]],
            };
            
            for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                [mainArray addObject:dict];
            }

            //organize data for third section: Working Status
            NSString *workStatusTitle[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.work-complete"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.inspection-result"],
                [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.follow-up-action"]
            };
            
            NSString *workStatusType[] = {
                [NSString stringWithFormat:@"%d",m_Work_Complete],
                [NSString stringWithFormat:@"%d",m_Inspection_Result],
                [NSString stringWithFormat:@"%d",m_Follow_Up_Action],
            };
            
            NSString *workStatusValue[] = {
                [itemDetailDict objectForKey:@"workComplete"],
                [itemDetailDict objectForKey:@"inspectionResult"],
                [itemDetailDict objectForKey:@"followAction"]
            };
            
            workCompleteSwitch.on = [[itemDetailDict objectForKey:@"workComplete"] boolValue];
            inspectionResultSwitch.on = [[itemDetailDict objectForKey:@"inspectionResult"] boolValue];
            followActionSwitch.on = [[itemDetailDict objectForKey:@"followAction"] intValue];
            
            for (int i=0;i < sizeof(workStatusTitle)/sizeof(workStatusTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:workStatusTitle[i],@"labelTitle",workStatusType[i],@"objectType",workStatusValue[i],@"objectValue", nil];
                [workStatusArray addObject:dict];
            }
        }
        else {
#pragma mark Add New Inspection
            NSString *objectValue[] = {
                [dictLanguage objectForKey:@"schedule.title-select"],
                @"",
                @"",
                [dictLanguage objectForKey:@"schedule.title-select-liaison"],
                @"1",
                @"1",
                @"1",
            };
            
            for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",objectValue[i],@"objectValue", nil];
                [mainArray addObject:dict];
            }
            
            //organize data for third section: Working Status
            NSString *workStatusTitle[] = {
                [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.work-complete"],
                [dictLanguage objectForKey:@"maintenance-mgmt.action.inspection-result"],
                [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.follow-up-action"]
            };
            
            NSString *workStatusType[] = {
                [NSString stringWithFormat:@"%d",m_Work_Complete],
                [NSString stringWithFormat:@"%d",m_Inspection_Result],
                [NSString stringWithFormat:@"%d",m_Follow_Up_Action],
            };
            
            NSString *workStatusValue[] = {
                @"0",
                @"0",
                @"0"
            };
            
            for (int i=0;i < sizeof(workStatusTitle)/sizeof(workStatusTitle[0]);i++) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:workStatusTitle[i],@"labelTitle",workStatusType[i],@"objectType",workStatusValue[i],@"objectValue", nil];
                [workStatusArray addObject:dict];
            }
        }
    }
    else {
        
        //organize data for third section: Working Status
        NSString *workStatusTitle[] = {
            [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.work-complete"],
        };
        
        NSString *workStatusType[] = {
            [NSString stringWithFormat:@"%d",m_Work_Complete],
        };
        
        NSString *workStatusValue[] = {
            [itemDetailDict objectForKey:@"workComplete"],
        };
        
        workCompleteSwitch.on = [[itemDetailDict objectForKey:@"workComplete"] boolValue];
        
        for (int i=0;i < sizeof(workStatusTitle)/sizeof(workStatusTitle[0]);i++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:workStatusTitle[i],@"labelTitle",workStatusType[i],@"objectType",workStatusValue[i],@"objectValue", nil];
            [workStatusArray addObject:dict];
        }
    }
    
    if ([[itemDetailDict objectForKey:@"workComplete"] boolValue]) {
        _btnRightCorner.hidden = YES;
    }
    
    titleContainerView.hidden = YES;
    
    _mainTableView.frame = CGRectMake(_mainTableView.frame.origin.x, _mainTableView.frame.origin.y-43, _mainTableView.frame.size.width, _mainTableView.frame.size.height+44);
}

- (void) viewWillAppear:(BOOL)animated {
    NSError *error;
    if (newInspectionId != nil) {
        [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:newInspectionId error:&error];
        if (!error) {
            NSLog(@"delete temporary new inspection successfully");
            newInspectionId = nil;
        }
        
        //reload previous inspection
        if (beforeInspectionSavedDict != nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeInspectionSavedDict error:&error];
            if (!error) {
                NSLog(@"reload previous Inspection successfully");
                beforeInspectionSavedDict = nil;
            }
        }
    }
    
    if (newScheduleId != nil) {
        [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:newScheduleId error:&error];
        if (!error) {
            NSLog(@"delete temporary new schedule successfully");
            newScheduleId = nil;
        }
        
        //reload previous schedule
        if (beforeScheduleSavedDict != nil) {
            [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:beforeScheduleSavedDict error:&error];
            if (!error) {
                NSLog(@"reload previous Schedule successfully");
                beforeScheduleSavedDict = nil;
            }
        }
    }
}

- (void) checkStatusOfDetail {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    int role = [[userDefaults objectForKey:USER_ROLE] intValue];
    
    //check current status of this maintenance
    //the sequence is below
    // - MA send request to Contractor -> status is "Waiting for Costing"
    // - Contractor send costing to MA -> status is "Costing Received"
    // - Owner Approve costing and send to MA -> status is "Costing Approved"
    // - Owner Reject costing and send to MA -> status is "Costing Rejected"
    // - MA send back approval to contractor and wait for work completion -> status is "Wait for work service"
    // - Owner receives COC and approves -> status is "Complete"
//    int status = [[itemDetailDict objectForKey:@"status"] intValue];
//    switch (status) {
//        case WAITING_FOR_COSTING:
//            //only contractor can interacts with this.
//            if (role == ROLE_MA || role == ROLE_OWNER) {
//                _btnRightCorner.hidden = YES;
//            }
//            break;
//        case COSTING_RECEIVED:
//            if (role == ROLE_MA || role == ROLE_CONTRACTOR) {
//                _btnRightCorner.hidden = YES;
//            }
//            break;
//        case COSTING_APPROVED:
//            if (role == ROLE_OWNER || role == ROLE_CONTRACTOR) {
//                _btnRightCorner.hidden = YES;
//            }
//            break;
//        case REJECT_QUOTATION:
//            if (role == ROLE_OWNER || role == ROLE_CONTRACTOR) {
//                _btnRightCorner.hidden = YES;
//            }
//            break;
//        case WAITING_FOR_WORK_SERVICE:
//            if (role == ROLE_MA || role == ROLE_CONTRACTOR)
//                _btnRightCorner.hidden = YES;
//            break;
//        case COMPLETE:
//            _btnRightCorner.hidden = YES;
//            break;
//        default:
//            break;
//    }
}

- (void) selectComboBox:(UIButton*)sender {
    int filterType = sender.tag;
    
    //init controller to filter value
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filterType];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void) selectDate:(UIButton*)sender {
    //dismiss popover before presenting another one
    [popoverController dismissPopoverAnimated:YES];
    
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date] paramSender:sender];
    controller.delegate = self;
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//    controller.datePicker.datePickerMode = UIDatePickerModeDate;
}

- (void) expandSection {
    NSRange range = NSMakeRange(2, 1);
    NSIndexSet *sectionToReload = [NSIndexSet indexSetWithIndexesInRange:range];
    [_mainTableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void) valueChangeFollowUpAction:(DCRoundSwitch*)sender {
    
}

- (void) valueChangeInspectionResult:(DCRoundSwitch*)sender {
    for (int i=0;i < [workStatusArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (DCRoundSwitch *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[DCRoundSwitch class]]) {
                if (subview.tag == sender.tag) {
                    NSMutableDictionary *dict = [workStatusArray objectAtIndex:i];
                    
                    [dict setObject:[NSNumber numberWithBool:sender.on] forKey:@"objectValue"];
                    
                    [self expandSection];
                    
                    break;
                }
            }
        }
    }
}

- (void) valueChangeWorkComplete:(DCRoundSwitch*)sender {
    for (int i=0;i < [workStatusArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (DCRoundSwitch *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[DCRoundSwitch class]]) {
                if (subview.tag == sender.tag) {
                    NSMutableDictionary *dict = [workStatusArray objectAtIndex:i];
                    
                    [dict setObject:[NSNumber numberWithBool:sender.on] forKey:@"objectValue"];
                    
                    [self expandSection];
                    
                    break;
                }
            }
        }
    }
}

- (void) valueChange:(DCRoundSwitch*)sender {
    if (!sender.isInit) {
        //set value to dictionary when switch
        BOOL isOK = NO;
        int index;
        for (int i=0;i < [mainArray count];i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
            UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
            
            for (DCRoundSwitch *subview in cell.contentView.subviews) {
                if ([subview isKindOfClass:[DCRoundSwitch class]]) {
                    if (subview.tag == sender.tag) {
                        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                        if (sender.tag != m_Costing) {
                            [dict setObject:[NSNumber numberWithBool:sender.on] forKey:@"objectValue"];
                        }
                        else {
                            NSString *objectValue = [dict objectForKey:@"objectValue"];
                            //structure of Costing field: FSR_field:Costing (Eg: FSR:1, Non FSR:1,...)
                            NSArray *tmpArray = [objectValue componentsSeparatedByString:@":"];
                            
                            //replace new value for FSR field
                            objectValue = [NSString stringWithFormat:@"%@:%@",[tmpArray objectAtIndex:0],[NSString stringWithFormat:@"%d",sender.on]];
                            
                            //set new value for dictionary
                            [dict setObject:objectValue forKey:@"objectValue"];
                        }
                        //reload cell
                        isOK = YES;
                        index = i;
                        break;
                    }
                }
            }
        }
        
        if (isOK) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
            NSMutableArray *indexPathArray = [NSMutableArray arrayWithObjects:indexPath, nil];
            [_mainTableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    sender.isInit = NO;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int superParent = [[userDefaults objectForKey:SUPER_PARENT] intValue];
    
    //if this view was loaded from Buidling Mgmt or Facility Mgmt flow
    if (superParent == BuildingMgmt){
        DetailedItemViewController *controller = [self.navigationController.viewControllers objectAtIndex:1];
        [controller.maintenanceController listInspectionAndMaintenance];
        [self.navigationController popToViewController:controller animated:YES];
    }
    else
        //if this view was loaded from Maintenance Mgmt flow
        [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark FilterViewDelegate

- (void) didSelectFilter:(NSMutableDictionary *)filterDict {
    [popoverController dismissPopoverAnimated:YES];
    int filterType = [[filterDict objectForKey:@"filterType"] intValue];
    
    //get all object in tableview and set value
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (UIButton *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[UIButton class]]) {
                if (subview.tag == filterType){
                    //get dictionary of this row
                    NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                    if (filterType == filter_fsr) {
                        NSString *objectValue = [dict objectForKey:@"objectValue"];
                        //structure of Costing field: FSR_field:Costing (Eg: FSR:1, Non FSR:1,...)
                        NSArray *tmpArray = [objectValue componentsSeparatedByString:@":"];
                        
                        //replace new value for FSR field
                        objectValue = [NSString stringWithFormat:@"%@:%@",[filterDict objectForKey:@"filterName"],[tmpArray objectAtIndex:1]];
                        
                        //set new value for dictionary
                        [dict setObject:objectValue forKey:@"objectValue"];
                    }
                    else if (filterType == filter_person_in_charge) {
                        personInChargeDict = filterDict;
                        [dict setObject:[filterDict objectForKey:@"filterName"] forKey:@"objectValue"];
                    }
                    else if (filterType == filter_inspection) {
                        typeRequirementDict = filterDict;
                        [dict setObject:[filterDict objectForKey:@"filterName"] forKey:@"objectValue"];
                    }
                    else {
                        [dict setObject:[filterDict objectForKey:@"filterName"] forKey:@"objectValue"];
                    }
                    [subview setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
                    break;
                }
            }
        }
    }
}

#pragma mark DatePickerViewDelegate
- (void) didCancelSectDatePicker {
    //do anything
    [popoverController dismissPopoverAnimated:YES];
}
//- (void) didSelectDatePicker:(NSDate *)date {
//    //do anything
//}
- (void) didSelectDatePicker:(NSDate *)date paramSender:(id)sender {
    [popoverController dismissPopoverAnimated:YES];
    
    UIButton *btnDate = (UIButton*)sender;
    
    //convert to MMM dd, yyyy
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a - MMM dd, yyyy"];
    
    [btnDate setTitle:[dateFormatter stringFromDate:date] forState:UIControlStateNormal];
    
    //save value into dictionary
    //get all object in tableview and set value
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (UIButton *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[UIButton class]]) {
                if (subview == sender){
                    //get dictionary of this row
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                    [dict setObject:[dateFormatter stringFromDate:date] forKey:@"objectValue"];
                    break;
                }
            }
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    [headerView setBackgroundColor:[UIColor whiteColor]];
    
    // Add the label
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.5, 200, 20)];
    headerLabel.font = [UIFont boldSystemFontOfSize:17];
    // do whatever headerLabel configuration you want here
    if (section == 0) {
        headerLabel.text = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.item"];
    }
    else if (section == 1) {
        headerLabel.text = [dictLanguage objectForKey:@"maintenance-mgmt.add-inspection.detail-title"];
    }
    else {
        headerLabel.text = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.status"];
    }

    [headerView addSubview:headerLabel];
    
    // Return the headerView
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return [itemInfoArray count];
    else if (section == 1)
        return [mainArray count];
    else {
        //get status of work complete
        for (int i=0;i < [workStatusArray count];i++) {
            NSMutableDictionary *dict = [workStatusArray objectAtIndex:i];
            int objectType = [[dict objectForKey:@"objectType"] intValue];
            if (objectType == m_Work_Complete) {
                int objectValue = [[dict objectForKey:@"objectValue"] intValue];
                if (objectValue == 0)
                    return 1;
            }
            else if (objectType == m_Inspection_Result) {
                int objectValue = [[dict objectForKey:@"objectValue"] intValue];
                if (objectValue == 0)
                    return 2;
            }
        }
        return [workStatusArray count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
        int objectType = [[dict objectForKey:@"objectType"] intValue];
        if (objectType == m_Costing)
            return _mainTableView.rowHeight*2;
    }
    return _mainTableView.rowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    static NSString *CellIdentifier = @"Cell";
    
    NSMutableDictionary *dict;
    
    if (indexPath.section == 0)
        dict = [itemInfoArray objectAtIndex:indexPath.row];
    else if (indexPath.section == 1)
        dict = [mainArray objectAtIndex:indexPath.row];
    else
        dict = [workStatusArray objectAtIndex:indexPath.row];
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 21)];
    lbTitle.backgroundColor = [UIColor clearColor];
    lbTitle.textColor = [UIColor darkGrayColor];
    lbTitle.text = [dict objectForKey:@"labelTitle"];
    [cell.contentView addSubview:lbTitle];
    
    int maintenanceStatus = [[itemDetailDict objectForKey:@"workComplete"] intValue];
    int objectType = [[dict objectForKey:@"objectType"] intValue];
    
    if (objectType == filter_start_date) {
        //button to choose date
        UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCombo.tag = objectType;
        btnCombo.frame = CGRectMake(495, 5, 354, 30);
        
        [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
        
        [btnCombo setTitle:[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"objectValue"]]] forState:UIControlStateNormal];
        [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];;
        
        if (isEdit) {
            cell.userInteractionEnabled = NO;
        }
        else {
            [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
            
            btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
            btnCombo.layer.borderWidth = 1.0;
            
            //add event handling for select date picker
            [btnCombo addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
            
            //add drop down image to end of button
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btnCalendar.png"]];
            imgView.frame = CGRectMake(310, -8, 44, 44);
            
            [btnCombo addSubview:imgView];
        }
        [cell.contentView addSubview:btnCombo];
    }
    else if (objectType == filter_end_date) {
        UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCombo.tag = objectType;
        btnCombo.frame = CGRectMake(495, 5, 354, 30);
        
        [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
        
        [btnCombo setTitle:[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"objectValue"]]] forState:UIControlStateNormal];
        [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];;
        
        [cell.contentView addSubview:btnCombo];
        cell.userInteractionEnabled = NO;
    }
    else if (objectType == filter_person_in_charge || objectType == filter_inspection) {
        UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCombo.frame = CGRectMake(495, 5, 354, 30);
        
        [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
        
        [btnCombo setTitle:[dict objectForKey:@"objectValue"] forState:UIControlStateNormal];
        [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
        
        if (isEdit) {
            cell.userInteractionEnabled = NO;
        }
        else {
            [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
            
            btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
            btnCombo.layer.borderWidth = 1.0;
            
            //get objectType and assign for button's tag
            btnCombo.tag = objectType;
            
            [btnCombo addTarget:self action:@selector(selectComboBox:) forControlEvents:UIControlEventTouchUpInside];
            
            //add drop down image to end of button
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
            imgView.frame = CGRectMake(330, 11, 13, 8);
            
            [btnCombo addSubview:imgView];
        }
        [cell.contentView addSubview:btnCombo];
    }
    else if (objectType == m_Work_Complete) {
        workCompleteSwitch.onText     = [dictLanguage objectForKey:@"general.yes"];
        workCompleteSwitch.offText    = [dictLanguage objectForKey:@"general.no"];
        [cell.contentView addSubview:workCompleteSwitch];
        
        //only MA,Admin can edit this action
//        NSString *role = [[userDefaults objectForKey:USER_ROLE] lowercaseString];
//        if ([role isEqualToString:@"ma"] || [role isEqualToString:@"admin"])
//            workCompleteSwitch.userInteractionEnabled = YES;
//        else
//            workCompleteSwitch.userInteractionEnabled = NO;
        if (maintenanceStatus && workCompleteSwitch.on && isEdit)
            workCompleteSwitch.userInteractionEnabled = NO;
    }
    else if (objectType == m_Inspection_Result) {
        inspectionResultSwitch.onText = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.result.passed"];
        inspectionResultSwitch.offText = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.result.failed"];
        [cell.contentView addSubview:inspectionResultSwitch];
        
        if (maintenanceStatus && workCompleteSwitch.on && isEdit)
            inspectionResultSwitch.userInteractionEnabled = NO;
    }
    else if (objectType == m_Follow_Up_Action) {
        followActionSwitch.onText     = [dictLanguage objectForKey:@"general.yes"];
        followActionSwitch.offText    = [dictLanguage objectForKey:@"general.no"];
        [cell.contentView addSubview:followActionSwitch];
        
        if (maintenanceStatus && workCompleteSwitch.on && isEdit)
            followActionSwitch.userInteractionEnabled = NO;
    }
    else if (objectType == m_Costing) {
        NSString *objectValue = [dict objectForKey:@"objectValue"];
        NSArray *valueArray = [objectValue componentsSeparatedByString:@":"];
        
        //add switch object
        DCRoundSwitch *mySwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(495, 75, 102, 30)];
        mySwitch.tag = objectType;
        mySwitch.onText     = [dictLanguage objectForKey:@"general.yes"];
        mySwitch.offText    = [dictLanguage objectForKey:@"general.no"];
        mySwitch.isInit = YES;
        [mySwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:mySwitch];
        
        @try {
            int status = [[valueArray objectAtIndex:1] intValue];
            mySwitch.on = status;
        }
        @catch (NSException *e) {
            NSLog(@"%@",e);
        }
        
        //init combobox button
        UIButton *btnCombo;
        
        if (maintenanceStatus != 1) {
            btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
            btnCombo.frame = CGRectMake(495, 5, 150, 30);
            [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
            [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
            [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
            
            [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            
            [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
            
            btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
            btnCombo.layer.borderWidth = 1.0;
            
            //get objectType and assign for button's tag
            btnCombo.tag = filter_fsr;
            
            [btnCombo addTarget:self action:@selector(selectComboBox:) forControlEvents:UIControlEventTouchUpInside];
            
            //add drop down image to end of button
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
            imgView.frame = CGRectMake(130, 11, 13, 8);
            
            [btnCombo addSubview:imgView];
            
            //only display button attach document and eform when switch ON
            if (mySwitch.on) {
                //add button attach document
                UIButton *btnAttach = [UIButton buttonWithType:UIButtonTypeCustom];
                btnAttach.tag = objectType;
                btnAttach.frame = CGRectMake(830, 65, 44, 44);
                [btnAttach setImage:[UIImage imageNamed:@"btnPlus.png"] forState:UIControlStateNormal];
                [btnAttach addTarget:self action:@selector(selectAddAttachDocument:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btnAttach];
                
                //add button eform
                UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
                btnEform.tag = btn_eform_costing;
                btnEform.frame = CGRectMake(650, 65, 44, 44);
                [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btnEform];
            }
            else {
                mySwitch.isInit = NO;
            }
        }
        else {
            mySwitch.userInteractionEnabled = NO;
            
            //maintenance has been already completed
            btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
            btnCombo.frame = CGRectMake(495, 5, 150, 30);
            [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            btnCombo.userInteractionEnabled = NO;
            
            //add button eform
            UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
            btnEform.tag = btn_eform_costing;
            btnEform.frame = CGRectMake(650, 65, 44, 44);
            [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
            [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:btnEform];
        }
        [btnCombo setTitle:[valueArray objectAtIndex:0] forState:UIControlStateNormal];
        [cell.contentView addSubview:btnCombo];
        
        
    }
    else if (objectType == m_Item_Label) {
        UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 800, 40)];
        lbTitle.backgroundColor = [UIColor clearColor];
        lbTitle.textColor = [UIColor darkGrayColor];
        lbTitle.text = [dict objectForKey:@"objectValue"];
        [cell.contentView addSubview:lbTitle];
        lbTitle.numberOfLines = 0;
        [lbTitle sizeToFit];
    }
    else if (objectType == m_Item_Name || objectType == m_Item_Description || objectType == m_Item_System) {
        UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(130, 10, 800, 21)];
        lbTitle.backgroundColor = [UIColor clearColor];
        lbTitle.textColor = [UIColor darkGrayColor];
        lbTitle.text = [dict objectForKey:@"objectValue"];
        [cell.contentView addSubview:lbTitle];
    }
    else if (objectType == m_Item_Location) {
        UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(130, 10, 800, 40)];
        lbTitle.backgroundColor = [UIColor clearColor];
        lbTitle.textColor = [UIColor darkGrayColor];
        lbTitle.text = [dict objectForKey:@"objectValue"];
        [cell.contentView addSubview:lbTitle];
        
        lbTitle.numberOfLines = 0;
        [lbTitle sizeToFit];
    }
    else {
        DCRoundSwitch *mySwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(495, 5, 102, 30)];
        mySwitch.tag = objectType;
        mySwitch.onText     = [dictLanguage objectForKey:@"general.yes"];
        mySwitch.offText    = [dictLanguage objectForKey:@"general.no"];
        mySwitch.isInit = YES;
        
        int status = [[dict objectForKey:@"objectValue"] intValue];
        mySwitch.on = status;
        
        [mySwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:mySwitch];
        
        if (maintenanceStatus != 1) {
            if (mySwitch.on) {
                //add button attach document
                UIButton *btnAttach = [UIButton buttonWithType:UIButtonTypeCustom];
                btnAttach.tag = objectType;
                btnAttach.frame = CGRectMake(830, 0, 44, 44);
                [btnAttach setImage:[UIImage imageNamed:@"btnPlus.png"] forState:UIControlStateNormal];
                [btnAttach addTarget:self action:@selector(selectAddAttachDocument:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btnAttach];
                
                
                //check to add button eform
                switch (objectType) {
                    case m_COC:
                    {
                        //add button eform
                        UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
                        btnEform.tag = btn_eform_coc;
                        btnEform.frame = CGRectMake(650, 0, 44, 44);
                        [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                        [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
                        [cell.contentView addSubview:btnEform];
                        break;
                    }
                    case m_Work_Request:
                    {
                        //add button eform
                        UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
                        btnEform.tag = btn_eform_work_request;
                        btnEform.frame = CGRectMake(650, 0, 44, 44);
                        [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                        [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
                        [cell.contentView addSubview:btnEform];
                        break;
                    }
                    default:
                        break;
                }
            }
            else {
                mySwitch.isInit = NO;
            }
        }
        else {
            //add button eform
            //check to add button eform
            switch (objectType) {
                case m_COC:
                {
                    //add button eform
                    UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
                    btnEform.tag = btn_eform_coc;
                    btnEform.frame = CGRectMake(650, 0, 44, 44);
                    [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                    [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
                    [cell.contentView addSubview:btnEform];
                    break;
                }
                case m_Work_Request:
                {
                    //add button eform
                    UIButton *btnEform = [UIButton buttonWithType:UIButtonTypeCustom];
                    btnEform.tag = btn_eform_work_request;
                    btnEform.frame = CGRectMake(650, 0, 44, 44);
                    [btnEform setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                    [btnEform addTarget:self action:@selector(selectEform:) forControlEvents:UIControlEventTouchUpInside];
                    [cell.contentView addSubview:btnEform];
                    break;
                }
                default:
                    break;
            }
            
            mySwitch.userInteractionEnabled = NO;
        }
    }
    
    //check permission for action on this row

    NSMutableDictionary *permissionDict;
    switch (objectType) {
        case m_Checklist:
            permissionDict = [userDefaults objectForKey:CHECKLIST_PERMISSION];
            break;
        case m_Technical_Assessment:
            permissionDict = [userDefaults objectForKey:TECHNICAL_ASSESSMENT_PERMISSION];
            break;
        case m_Report:
            permissionDict = [userDefaults objectForKey:REPORTING_PERMISSION];
            break;
        case m_Work_Request:
            permissionDict = [userDefaults objectForKey:WORK_REQUEST_PERMISSION];
            break;
        case m_Costing:
            permissionDict = [userDefaults objectForKey:COSTING_PERMISSION];
            break;
        case m_Approval:
            permissionDict = [userDefaults objectForKey:APPROVAL_PERMISSION];
            break;
        case m_EPO:
            permissionDict = [userDefaults objectForKey:EPO_PERMISSION];
            break;
        case m_RAP:
            permissionDict = [userDefaults objectForKey:RAP_PERMISSION];
            break;
        case m_COC:
            permissionDict = [userDefaults objectForKey:COC_PERMISSION];
            break;
        case m_GR:
            permissionDict = [userDefaults objectForKey:GR_PERMISSION];
            break;
        case m_Invoice:
            permissionDict = [userDefaults objectForKey:INVOICE_PERMISSION];
            break;
        case m_ETO:
            permissionDict = [userDefaults objectForKey:ETO_PERMISSION];
            break;
        case m_Work_Complete:
            permissionDict = [userDefaults objectForKey:WORK_COMPLETE_PERMISSION];
            break;
        default:
            break;
    }
    
    //only check permission for these objectype
    switch (objectType) {
        case m_Checklist:
        case m_Technical_Assessment:
        case m_Report:
        case m_Work_Request:
        case m_Costing:
        case m_Approval:
        case m_EPO:
        case m_RAP:
        case m_COC:
        case m_GR:
        case m_Invoice:
        case m_ETO:
        {
            NSString *maintenanceId;
            //check attachment document which was attached in this action
            if (isEdit)
                maintenanceId = [itemDetailDict objectForKey:@"_id"];
            else {
                if (serviceType == Inspection)
                    maintenanceId = [inputInspectionDict objectForKey:@"_id"];
                else
                    maintenanceId = [inputMaintenanceDict objectForKey:@"_id"];
            }
            
            NSMutableArray *attachmentArray = [CouchBaseLiteLib listAttachmentByMaintenance:maintenanceId andType:objectType];
            
            if ([attachmentArray count] > 0) {
                //add button to show attachment document
                UIButton *btnAttach = [UIButton buttonWithType:UIButtonTypeCustom];
                btnAttach.tag = objectType;
                
                if (objectType == m_Costing)
                    btnAttach.frame = CGRectMake(750, 65, 44, 44);
                else
                    btnAttach.frame = CGRectMake(750, 0, 44, 44);
                [btnAttach setImage:[UIImage imageNamed:@"btnForm.png"] forState:UIControlStateNormal];
                [btnAttach addTarget:self action:@selector(selectAttachDocument:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btnAttach];
                
                CircleView *cirleNotification = [[CircleView alloc] initWithFrame:CGRectMake(30, 5, 15, 15)];
                [btnAttach addSubview:cirleNotification];
                
                UILabel *lbNotification = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
                lbNotification.font = [UIFont systemFontOfSize:11];
                lbNotification.textAlignment = NSTextAlignmentCenter;
                lbNotification.textColor = [UIColor whiteColor];
                lbNotification.backgroundColor = [UIColor clearColor];
                lbNotification.text = [NSString stringWithFormat:@"%d",[attachmentArray count]];
                [cirleNotification addSubview:lbNotification];
            }
            
//            BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
//            if (!isEditable) {
//                cell.userInteractionEnabled = NO;
//            }
            break;
        }
        case m_Work_Complete:
        {
            BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
            if (!isEditable) {
                cell.userInteractionEnabled = NO;
            }
            break;
        }
        default:
            break;
    }
    
//    if (serviceType == Inspection && isEdit)
//        cell.userInteractionEnabled = NO;
    
    return cell;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void) selectEform:(UIButton*)sender {
    NSMutableDictionary *permissionDict;
    NSString *formType = @"";
    switch (sender.tag) {
        case btn_eform_work_request:
            formType = @"wr";
            permissionDict = [[NSUserDefaults standardUserDefaults] objectForKey:WORK_REQUEST_PERMISSION];
            break;
        case btn_eform_coc:
            formType = @"coc";
            permissionDict = [[NSUserDefaults standardUserDefaults] objectForKey:COC_PERMISSION];
            break;
        case btn_eform_costing:
        {
            permissionDict = [[NSUserDefaults standardUserDefaults] objectForKey:COSTING_PERMISSION];
            BOOL isFSR = NO;
            //loop mainArray and check FSR or non FSR
            for (int i=0;i < [mainArray count];i++) {
                NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                int objectType = [[dict objectForKey:@"objectType"] intValue];
                if (objectType == m_Costing) {
                    NSString *objectValue = [dict objectForKey:@"objectValue"];
                    NSArray *tmpArray = [objectValue componentsSeparatedByString:@":"];
                    NSString *fsr = [[tmpArray objectAtIndex:0] lowercaseString];
                    if ([fsr isEqualToString:@"fsr"])
                        isFSR = YES;
                    break;
                }
            }
            //call webservice to load eForm
            if (isFSR)
                formType = @"fsr";
            else
                formType = @"nonFsr";
            break;
        }
        default:
            break;
    }
    
    //get eform by maintenance
    NSMutableDictionary *argument;
    int status = [[itemDetailDict objectForKey:@"workComplete"] intValue];
    NSString *maintenanceId;
    if (isEdit) {
        maintenanceId = [itemDetailDict objectForKey:@"_id"];
        maintenanceTypeId = [[itemDetailDict objectForKey:@"maintenanceTypeId"] intValue];
        
        argument = [NSMutableDictionary dictionaryWithObjectsAndKeys:maintenanceId,@"maintenanceId",[NSNumber numberWithInt:maintenanceTypeId],@"maintenanceType",formType,@"documentType",[itemDetailDict objectForKey:@"itemId"],@"idItem",[NSNumber numberWithInteger:status],@"status", nil];
    }
    else {
        maintenanceId = [inputMaintenanceDict objectForKey:@"_id"];
        
        //status = 1 to hide submit button
        argument = [NSMutableDictionary dictionaryWithObjectsAndKeys:maintenanceId,@"maintenanceId",[NSNumber numberWithInt:maintenanceTypeId],@"maintenanceType",formType,@"documentType",[itemDetailDict objectForKey:@"itemId"],@"idItem",[NSNumber numberWithInteger:1],@"status", nil];
    }
    
    //push eform first, then reload after responsing data
    EformViewController *controller = [[EformViewController alloc] initWithNibName:@"EformViewController" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
    
    //firstly, get eform detail, if hasnt existed eform, load new eform
    
    NSMutableDictionary *detailEformArgument = [NSMutableDictionary dictionaryWithObjectsAndKeys:maintenanceId,@"maintenanceId",formType,@"documentType", [NSNumber numberWithInt:status],@"status",nil];
    
    //status = 1 to hide submit button, FMS-442
    BOOL isUpdate = [[permissionDict objectForKey:@"update"] boolValue];
    if (!isUpdate) {
        [detailEformArgument setObject:[NSNumber numberWithInt:1] forKey:@"status"];
        [argument setObject:[NSNumber numberWithInt:1] forKey:@"status"];
    }
    
    [[FMSServerAPI shareClient] getDetailedEform:detailEformArgument successs:^(NSMutableDictionary *response) {
        NSMutableDictionary *dict = (NSMutableDictionary *)response;
        if ([dict objectForKey:@"response"] == nil || [[dict objectForKey:@"response"] count] == 0) {
            //not exist this form
            [[FMSServerAPI shareClient] getEformByType:argument successs:^(NSMutableDictionary *response) {
                if ([response isKindOfClass:[NSMutableDictionary class]]) {
                    NSMutableDictionary *dict = (NSMutableDictionary *)response;
                    if ([[[dict objectForKey:@"meta"] objectForKey:@"code"] intValue] == 200) {
                        //success
                        if ([[dict objectForKey:@"response"] count] > 0) {
                            NSMutableDictionary *eFormDict = [[dict objectForKey:@"response"] mutableCopy];
                            if (eFormDict != Nil){
                                //if is Edit action, get maintenanceId from itemDetailDict
                                //otherwise, if is Add action, get maintenanceId from inputMaintenanceDict
                                if (isEdit)
                                    [eFormDict setObject:[itemDetailDict objectForKey:@"_id"] forKey:@"maintenanceId"];
                                else
                                    [eFormDict setObject:[inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
                                controller.eFormDict = eFormDict;
                                [controller reloadEform];
                            }
                            else {
                                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance.eform.not-existence"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                                [dialog show];
                            }
                        }
                        else {
                            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"maintenance.eform.not-existence"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                            [dialog show];
                        }
                    }
                    else {
                        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.server-not-response"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                    }
                }
            } failure:^(NSError *error) {
                NSLog(@"error = %@",error);
            }];
        }
        else {
            NSMutableArray *tmpArray = [dict objectForKey:@"response"];
            if ([tmpArray count] > 0) {
                NSMutableDictionary *documentDict = [tmpArray objectAtIndex:0];
                
                [controller getDetailEform:[documentDict objectForKey:@"content"]];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void) selectAddAttachDocument:(UIButton*)sender {
    currentAttachDocumentType = sender.tag;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *permissionDict;
    switch (currentAttachDocumentType) {
        case m_Checklist:
            permissionDict = [userDefaults objectForKey:CHECKLIST_PERMISSION];
            break;
        case m_Technical_Assessment:
            permissionDict = [userDefaults objectForKey:TECHNICAL_ASSESSMENT_PERMISSION];
            break;
        case m_Report:
            permissionDict = [userDefaults objectForKey:REPORTING_PERMISSION];
            break;
        case m_Work_Request:
            permissionDict = [userDefaults objectForKey:WORK_REQUEST_PERMISSION];
            break;
        case m_Costing:
            permissionDict = [userDefaults objectForKey:COSTING_PERMISSION];
            break;
        case m_Approval:
            permissionDict = [userDefaults objectForKey:APPROVAL_PERMISSION];
            break;
        case m_EPO:
            permissionDict = [userDefaults objectForKey:EPO_PERMISSION];
            break;
        case m_RAP:
            permissionDict = [userDefaults objectForKey:RAP_PERMISSION];
            break;
        case m_COC:
            permissionDict = [userDefaults objectForKey:COC_PERMISSION];
            break;
        case m_GR:
            permissionDict = [userDefaults objectForKey:GR_PERMISSION];
            break;
        case m_Invoice:
            permissionDict = [userDefaults objectForKey:INVOICE_PERMISSION];
            break;
        case m_ETO:
            permissionDict = [userDefaults objectForKey:ETO_PERMISSION];
            break;
        case m_Work_Complete:
            permissionDict = [userDefaults objectForKey:WORK_COMPLETE_PERMISSION];
            break;
        default:
            break;
    }
    
    BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
    if (!isAdd) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:Nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    if (popController != nil) {
        [popController dismissPopoverAnimated:YES];
        popController = nil;
    }
    imagePickerController = [[UIImagePickerController alloc] init];
    NSArray *mediaTypes;
    NSString *requiredMediaType = (NSString *)kUTTypeImage;
    
    mediaTypes = [NSArray arrayWithObject:requiredMediaType];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.mediaTypes = mediaTypes;
    imagePickerController.allowsEditing = YES;
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
    popController = popover;
    popController.delegate = self;
    [popController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    
    imagePickerController = nil;
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void) selectAttachDocument:(UIButton*)sender {
    int attachDocumentType = sender.tag;
    currentAttachDocumentType = attachDocumentType;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *permissionDict;
    switch (currentAttachDocumentType) {
        case m_Checklist:
            permissionDict = [userDefaults objectForKey:CHECKLIST_PERMISSION];
            break;
        case m_Technical_Assessment:
            permissionDict = [userDefaults objectForKey:TECHNICAL_ASSESSMENT_PERMISSION];
            break;
        case m_Report:
            permissionDict = [userDefaults objectForKey:REPORTING_PERMISSION];
            break;
        case m_Work_Request:
            permissionDict = [userDefaults objectForKey:WORK_REQUEST_PERMISSION];
            break;
        case m_Costing:
            permissionDict = [userDefaults objectForKey:COSTING_PERMISSION];
            break;
        case m_Approval:
            permissionDict = [userDefaults objectForKey:APPROVAL_PERMISSION];
            break;
        case m_EPO:
            permissionDict = [userDefaults objectForKey:EPO_PERMISSION];
            break;
        case m_RAP:
            permissionDict = [userDefaults objectForKey:RAP_PERMISSION];
            break;
        case m_COC:
            permissionDict = [userDefaults objectForKey:COC_PERMISSION];
            break;
        case m_GR:
            permissionDict = [userDefaults objectForKey:GR_PERMISSION];
            break;
        case m_Invoice:
            permissionDict = [userDefaults objectForKey:INVOICE_PERMISSION];
            break;
        case m_ETO:
            permissionDict = [userDefaults objectForKey:ETO_PERMISSION];
            break;
        case m_Work_Complete:
            permissionDict = [userDefaults objectForKey:WORK_COMPLETE_PERMISSION];
            break;
        default:
            break;
    }
    
    int status = [[itemDetailDict objectForKey:@"workComplete"] intValue];
    
    ListMaintenanceAttachmentViewController *controller = [[ListMaintenanceAttachmentViewController alloc] initWithNibName:@"ListMaintenanceAttachmentViewController" bundle:nil parent:self];
    if (isEdit) {
        controller.maintenanceId = [itemDetailDict objectForKey:@"_id"];
    }
    else {
        if (serviceType == Inspection)
            controller.maintenanceId = [inputInspectionDict objectForKey:@"_id"];
        else
            controller.maintenanceId = [inputMaintenanceDict objectForKey:@"_id"];
    }
    controller.permissionDict = permissionDict;
    controller.maintenanceTypeId = attachDocumentType;
    
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:controller];
    popController = popover;
    [popController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    
    //check display or not button select
    
    if (status)
        controller.btnSelect.hidden = YES;
}

#pragma mark UIImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    
    //create document to save photo for this item
    NSData *fileData;
    NSString *lastChosenMediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        fileData = UIImageJPEGRepresentation(chosenImage, 1.0);
    }
    
    NSString *maintenanceId;
    if (isEdit)
        maintenanceId = [itemDetailDict objectForKey:@"_id"];
    else {
        if (serviceType == Inspection)
            maintenanceId = [inputInspectionDict objectForKey:@"_id"];
        else
            maintenanceId = [inputMaintenanceDict objectForKey:@"_id"];
    }
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *todayStr = [dateFormatter stringFromDate:today];
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@",[info objectForKey:UIImagePickerControllerReferenceURL]];
    
    //name for this document by today
    NSString *fileName = todayStr;
    
    NSMutableDictionary *fileDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:todayStr,@"dateUploaded",imageUrl,@"imageUrl",[NSNumber numberWithInt:currentAttachDocumentType],@"attachDocumentType",fileName,@"fileName",MaintenanceAttachment,@"Table",maintenanceId,@"maintenanceId", nil];
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] createDocumentWithAttachment:fileDict fileData:fileData error:&error];
    if (!error) {
        //set flag to mark this type: checklist, technical assessment,... is was add document
        [self reloadMaintenanceAttachment];
        
        [popController dismissPopoverAnimated:YES];
        popController = nil;
    }
    
    [self performSelector:@selector(hideStatusBar) withObject:self afterDelay:1.0];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [popController dismissPopoverAnimated:YES];
    popController = nil;
    
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

- (void) hideStatusBar {
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

- (void) dismissPopoverController {
    [popController dismissPopoverAnimated:YES];
    popController = nil;
}

#pragma mark UIPopoverControllerDelegate

- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {
    return YES;
}
- (void) popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    //hide status bar after select image
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    else
    {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
}

- (BOOL) prefersStatusBarHidden {
    return YES;
}

- (void) reloadMaintenanceAttachment {
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        NSArray *indexPathArray = [NSArray arrayWithObjects:indexPath, nil];
        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
        int objectType = [[dict objectForKey:@"objectType"] intValue];
        
        if (objectType == currentAttachDocumentType) {
            [_mainTableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        }
    }
}

- (void) dealloc {
    NSLog(@"%@ dealloc",self);
    _delegate = nil;
    parent = nil;
    itemDetailDict = nil;
    _mainTableView = nil;
    _lbMainTitle = nil;
    _btnBack = nil;
    _btnRightCorner = nil;
    _btnInspection = nil;
    _btnMaintenance = nil;
    mainArray = nil;
}

@end
